繁体   English   中英

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

[英]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.仅当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的文档,并找到“负超前断言”的文档。

输出:

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

请尝试以下操作:

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)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM