我需要找到单词“ test”何时出现,然后是“ follow”,中间没有其他“ test”。
例子:
test
word
word
word
test
test
word
word
follow
word
word
test
我只想要这个:
test
word
word
word
test
**test**
**word**
**word**
**follow**
word
word
test
我对正则表达式还不够熟悉,无法做到这一点。任何建议都很好。
编辑虽然单词test将在其中多次出现,但是单词follow将仅在字符串中出现一次。
您将需要正则表达式在这里使用前瞻。
test(?:\w|\s(?!test))+?follow
(?:)
是一个非捕获组。\w
匹配任何单词字符[a-zA-Z0-9_]
。\s
匹配任何空格(包括换行符)。\s(?!test)
仅匹配不跟在后面的换行符test
(在正则表达式中称为负前瞻)。()+?
只是使比赛变得非贪婪。
带有匹配项的测试输入:
test
word
**test**
**word**
**follow**
word
test
**test**
**word**
**word**
**follow**
word
word
**test**
**word**
**follow**
(?<!\w)(test)\s(?!\1\s)(?:\w|\s(?!\1\s))*?(?<!\w)follow(?!\w)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句