Swift 3替换出现正则表达式

Den*_*nis 4 regex swift

我的replacementOccurrences函数遇到了问题.我有一个像这样的字符串:

let x = "&john &johnny &johnney"
Run Code Online (Sandbox Code Playgroud)

我需要做的是只删除"&john"

所以我有这个代码:

y = "&john"
x = x.replacingOccurrences(of: y, with: " ", options: NSString.CompareOptions.regularExpression, range: nil)
Run Code Online (Sandbox Code Playgroud)

我得到的问题是,这删除了约翰的所有实例...而且我留下了:

"ny ney"
Run Code Online (Sandbox Code Playgroud)

此外,我考虑设置范围,然而,这不会真正解决我的问题,因为名称可能是不同的顺序.

vad*_*ian 6

首先,你的代码不能编译,因为x必须var.

要仅&John使用正则表达式删除,您需要检查查询的结尾是否为单词边界:

var x = "&john &johnny &johnney"

let pattern = "&john\\b"
x = x.replacingOccurrences(of: pattern, with: " ", options: .regularExpression)
Run Code Online (Sandbox Code Playgroud)


Sim*_*eat -2

您可能需要在要删除的字符串末尾包含一个空格:

y = "&john "