Search code examples
swiftswift-string

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.


Solution

  • 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