【问题标题】:Swift replace occurrence of string with conditionSwift用条件替换字符串的出现
【发布时间】:2019-06-20 16:31:52
【问题描述】:

我有如下字符串

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

我得到像

这样的输出

&lt;p&gt;&lt;weak&gt;I am a weakPerson&lt;/weak&gt;&lt;/p&gt;

但我需要这样的输出

&lt;p&gt;&lt;strong&gt;I am a weakPerson&lt;/strong&gt;&lt;/p&gt;

我的条件是

1.只有当单词不包含“”这样的HTML标签时才需要替换。

帮我拿到它。提前致谢。

【问题讨论】:

  • 这很容易用正则表达式
  • @Sh_Khan 你能帮我写正则表达式吗?

标签: swift swift-string


【解决方案1】:

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

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)

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

诀窍是使用(?!&gt;),这基本上意味着忽略任何以&amp;gt;结尾的匹配项。查看NSRegularExpression 的文档并找到“否定前瞻断言”的文档。

输出:

我是一个弱者

【讨论】:

  • 我建议您也使用否定的look-behind 以避免匹配"strong&gt;",因此正则表达式将是"(?&lt;!&lt;|&lt;\/)strong(?!&gt;)"。解释这个的链接在这里:regexr.com/4g5o4
  • @Sam 我假设您永远不会在字符串中找到strong&gt;,因为&amp;gt; 将输入为&amp;gt;
  • @Sam 这个字符串 "\" 显示错误,文字中的转义序列无效
  • 在 Swift 字符串中你需要"(?&lt;!&lt;|&lt;\\/)string(?!&gt;)"。注意双反斜杠。
  • @Manimurugan 完全正确
【解决方案2】:

尝试以下方法:

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

【讨论】:

  • 为什么不区分大小写?
  • &lt;p&gt;&lt;strong&gt;I am a StrongPerson&lt;/strong&gt;&lt;/p&gt;的情况下,以及我在我的一个文件中有它,所以他可以省略它
  • 但随后StrongPerson 变为weakPerson 而不是WeakPerson。这可能是也可能不是 OP 想要的。
  • 谢谢你的留言,我就省略了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-08
  • 2014-03-13
  • 2016-06-24
  • 2011-10-03
  • 2017-04-09
  • 1970-01-01
相关资源
最近更新 更多