使用条件快速替换出现的字符串

时间:2019-06-20 16:31:52

标签: swift swift-string

我有下面这样的字符串

<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。仅当word不包含这些HTML标记(例如“ <>”)时,才必须替换。

帮我得到它。预先感谢。

2 个答案:

答案 0 :(得分: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)

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

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

输出:

  

我是一个弱者

答案 1 :(得分: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)
}