-1

I'm locked in a regex problem. I must put "<strong>" and "</strong>" tags at the sides of some String, along a larger String. For example, if I have:

"This is a test, and test word appears two times"

And the String selected is "test", it will remains:

"This is a <_strong>test<_/strong>, and <_strong>test<_/strong> word appears two times"

At first, I think in use regex functions combined with "ReplacedAll". The problem comes when there are <_strong> tags in the larger String, some like that:

"This is a test, and <_strong>test word<_/strong> appears two times"

It will remain something like that:

"This is a <_strong>test<_/strong>, and <_strong><_strong>test<_/strong> word<_/strong> appears two times"

The idea is for find a regular expression that modify the string "test" only if there isn't between <_strong> tags. But I'm not able for find it.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Esporas
  • 11
  • 5

1 Answers1

2

You can use double negative lookaheads for this:

test(?!(?:(?!<_strong>).)*<_/strong>)

regex101 demo

This makes sure that the test is not followed by a <_/strong> (unless there's an opening <_strong> in between).

(?! ... ) is a negative lookahead. It prevents a match if the previous expression is followed by the expression inside the negative lookahead.

E.g.

a(?!b) will match all a not followed by b.

(?!(?:(?!<_strong>).)*<_/strong>) has two negative lookaheads. First we could say that there is (?!.*<_/strong>). When you have test(?!.*<_/strong>), this will match all test unless they have a <_/strong> after them. Now, this wouldn't work for the second sentence because even the first test has a <_/strong> after it.

The trick is that a test is considered to be within <_strong> tags only if there isn't an opening <_strong> tag between test and <_/strong>. That is where the .* turned into (?:(?!<_strong>).)*

You can play around in the regex101 demo site I linked in my answer earlier.

Jerry
  • 70,495
  • 13
  • 100
  • 144
  • Thank you, that code works perfectly. However I'm below in knowledge that a noob. Can you explain me how it works exactly? – Esporas Sep 26 '13 at 02:44
  • @user2814276 I added some more explanation to my answer, if it helps – Jerry Sep 26 '13 at 05:16