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

标签 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标签时才需要替换。

帮我搞定。提前致谢。

最佳答案

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

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/

相关文章:

ios - 在 iOS 中使用 Firebase 数据库检索数据

ios - 如何在XMPP中接受好友请求?

dictionary - 如何从 Swift 中的字典中获取键的值?

ios - 向tableView中添加不同的继承对象

ios - 静态成员不能用于协议(protocol)元类型

swift - 什么是 String.Encoding.unicode?

快速转义反斜杠不能按预期工作

arrays - 如何在 Swift 中转换字符串?