简体   繁体   English

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

[英]Swift replace occurrence of string with condition

I have string like below 我有下面的字符串

<p><strong>I am a strongPerson</strong></p>

I want to covert this string like this 我想像这样隐蔽这个字符串

<p><strong>I am a weakPerson</strong></p>

When I try below code 当我尝试下面的代码

let old = "<p><strong>I am a strongPerson</strong></p>"
let new = old.replacingOccurrences(of: "strong", with: "weak")
print("\(new)")

I am getting output like 我正在输出像

<p><weak>I am a weakPerson</weak></p>

But I need output like this 但是我需要这样的输出

<p><strong>I am a weakPerson</strong></p>

My Condition here is 我的条件是

1.It has to replace only if word does not contain these HTML Tags like "<>". 1.仅当word不包含这些HTML标记(例如“ <>”)时才必须替换。

Help me to get it. 帮帮我。 Thanks in advance. 提前致谢。

You can use a regular expression to avoid the word being in a tag: 您可以使用正则表达式来避免单词出现在标签中:

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)

I added some extra uses of the word "strong" to test edge cases. 我添加了“强”一词的一些额外用法来测试极端情况。

The trick is the use of (?!>) which basically means to ignore any match that has a > at the end of it. 诀窍是使用(?!>) ,这基本上意味着忽略任何结尾有>匹配项。 Look at the documentation for NSRegularExpression and find the documentation for the "negative look-ahead assertion". 查看NSRegularExpression的文档,并找到“负超前断言”的文档。

Output: 输出:

weak <p><strong>I am a weak person</strong></p> weak 弱<p> <strong>我是一个弱者</ strong> </ p>

Try the following: 请尝试以下操作:

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