简体   繁体   中英

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

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

Output:

weak <p><strong>I am a weak person</strong></p> weak

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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