0

我有如下字符串

<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.仅当单词不包含“<>”之类的HTML标签时才需要替换。

帮我搞定。提前致谢。

4

2 回答 2

3

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

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)

我添加了“强”这个词的一些额外用法来测试边缘情况。

诀窍是使用(?!>)它基本上意味着忽略任何以 a>结尾的匹配项。查看文档NSRegularExpression并找到“负前瞻断言”的文档。

输出:

弱<p><strong>我是一个弱者</strong></p>弱

于 2019-06-20T16:45:01.313 回答
1

尝试以下操作:

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)
}
于 2019-06-20T16:47:33.467 回答