gpt4 book ai didi

Swift 3 replacingOccurrences 精确

转载 作者:行者123 更新时间:2023-11-28 15:42:33 30 4
gpt4 key购买 nike

我的 replacingOccurrences 函数有问题。我有一个这样的字符串:

let x = "john, johnny, johnney"

我需要做的只是删除“john”

所以我有这段代码:

y = "john"
x = x.replacingOccurrences(of: y, with: " ", options: NSString.CompareOptions.literal, range: nil)

我遇到的问题是,这会删除 john 的所有实例...我还考虑过设置范围,但是,这并不能真正解决我的问题,因为名称的顺序可能不同。

是否有一个我忽略了“精确”的 CompareOptions 函数,或者我是否需要创建一个正则表达式?

此致

丹尼斯·安吉尔

最佳答案

您应该使用正则表达式来匹配确切的词,您只需将所需的词放在\b 之间。像这样尝试:

let x = "johnny, john, johnney"
let y = "john"
let z = x.replacingOccurrences(of: "\\b\(y)\\b", with: " ", options: .regularExpression) // "johnny, , johnney"

let x =  "johnny &john johnney"
let y = "&john"
let z = x.replacingOccurrences(of: y + "\\b", with: " ", options: .regularExpression)

关于Swift 3 replacingOccurrences 精确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43553425/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com