Swift 用条件替换出现的字符串

Swift replace occurrence of string with condition

我有如下字符串

<p><strong>I am a strongPerson</strong></p>

我想像这样隐藏这个字符串

<p><strong>I am a weakPerson</strong></p>

当我尝试下面的代码时

let old = "<p><strong>I am a strongPerson</strong></p>"
let new = old.replacingOccurrences(of: "strong", with: "weak")
print("\(new)")

我得到的输出类似于

<p><weak>I am a weakPerson</weak></p>

但我需要这样的输出

<p><strong>I am a weakPerson</strong></p>

我这里的条件是

1.It 仅当单词不包含这些 HTML 标签(如“<>”)时才需要替换。

帮我拿下。提前致谢。

您可以使用正则表达式来避免单词出现在标签中:

let old = "strong <p><strong>I am a strong person</strong></p> strong"
let new = old.replacingOccurrences(of: "strong(?!>)", with: "weak", options: .regularExpression, range: nil)
print(new)

我添加了单词 "strong" 的一些额外用法来测试边缘情况。

诀窍是使用 (?!>),这基本上意味着忽略任何末尾有 > 的匹配项。查看 NSRegularExpression 的文档并找到 "negative look-ahead assertion".

的文档

输出:

weak <p><strong>I am a weak person</strong></p> weak

尝试以下操作:

let myString = "<p><strong>I am a strongPerson</strong></p>"
if let regex = try? NSRegularExpression(pattern: "strong(?!>)") {

 let modString = regex.stringByReplacingMatches(in: myString, options: [], range: NSRange(location: 0, length:  myString.count), withTemplate: "weak")
  print(modString)
}