0

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.

Mani murugan
  • 1,792
  • 2
  • 17
  • 32

2 Answers2

3

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

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 2
    I recommend that you also use a negative look-behind to avoid matching `"strong>"`, so the regular expression would then be `"(?<!<|<\/)strong(?!>)"`. A link to explain this is here: regexr.com/4g5o4 – Sam Jun 20 '19 at 16:51
  • 1
    @Sam I was assuming you would never find `strong>` in the string because the `>` would be entered as `>`. – rmaddy Jun 20 '19 at 16:52
  • @Sam It shows error for this string "\" , Invalid escape sequence in literal – Mani murugan Jun 20 '19 at 16:56
  • 1
    In a Swift string you would need `"(?<!<|<\\/)string(?!>)"`. Note the double backslash. – rmaddy Jun 20 '19 at 16:57
  • 1
    @Manimurugan Exactly – Sam Jun 20 '19 at 16:58
1

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)
}
Abdulrahman Falyoun
  • 3,676
  • 3
  • 16
  • 43