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

4

1 回答 1

2

您可以为此使用双重否定前瞻:

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

正则表达式101演示

这确保了test后面不跟 a <_/strong>(除非<_strong>中间有一个开口)。

(?! ... )是负前瞻。如果前一个表达式后跟否定前瞻内的表达式,它会阻止匹配。

例如

a(?!b)将匹配所有a不跟随的b.

(?!(?:(?!<_strong>).)*<_/strong>)有两个负前瞻。首先我们可以说有(?!.*<_/strong>)。当你有 时test(?!.*<_/strong>),这将匹配所有test,除非他们<_/strong>后面有一个。现在,这不适用于第二句,因为即使第test一句后面也有一个<_/strong>

诀窍是只有在和之间没有开始标签时才认为a在标签test内。那是变成<_strong><_strong>test<_/strong>.*(?:(?!<_strong>).)*

您可以在我之前在我的答案中链接的 regex101 演示站点中玩耍。

于 2013-09-25T12:04:18.937 回答