我有如下字符串
<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标签时才需要替换。
帮我搞定。提前致谢。
最佳答案
您可以使用正则表达式来避免单词出现在标签中:
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)
我添加了“强”这个词的一些额外用法来测试边缘情况。
诀窍是使用(?!>)
,这基本上意味着忽略任何结尾有>
的匹配项。查看 NSRegularExpression
的文档并找到“negative look-ahead assertion”的文档。
输出:
weak <p><strong>I am a weak person</strong></p> weak
关于Swift 用条件替换字符串的出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56690381/