1

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.

2
  • 1
    this is easily with a regular expression Commented Jun 20, 2019 at 16:39
  • @Sh_Khan Can you please kindly help me to write Regular Expression? Commented Jun 20, 2019 at 16:40

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

5 Comments

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 I was assuming you would never find strong> in the string because the > would be entered as &gt;.
@Sam It shows error for this string "\" , Invalid escape sequence in literal
In a Swift string you would need "(?<!<|<\\/)string(?!>)". Note the double backslash.
@Manimurugan Exactly
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)
}

4 Comments

Why case insensitive?
In case of <p><strong>I am a StrongPerson</strong></p>, As well as i have it in one of my file so he can omit it
But then StrongPerson becomes weakPerson and not WeakPerson. That may or may not be what the OP wants.
Thanks for your note, I'll omit it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.