[英]Regex match everything except word
All QA about matching something except word with negative look-ahead that I found imply lines start/end( ^
$
). 所有关于匹配某些东西的质量检查, 除了带有负向超前的单词 ,我发现这暗示着行的开始/结束(
^
$
)。 But I can't figure out how can I match everything (any character like .*
) except word before some other word in the middle of the processed text. 但是我不知道如何匹配除已处理文本中间的其他单词之前的单词以外的所有内容(
.*
等任何字符)。
I should match ABC
inside <tag></tag>
: 我应该在
<tag></tag>
匹配ABC
:
...<tag>a a.__aABC&*</tag>aaa<tag>ffff</tag>...
but not outside (false-positive): 但不在外面(假阳性):
...<tag>a a.__a&*</tag>ABC<tag>ffff</tag>...
So I think I should exclude tag closing ( </tag>
) before ABC
. 因此,我认为我应该排除
ABC
之前的标签关闭( </tag>
)。 I tried: 我试过了:
<tag>(?!<\/tag>)ABC.*?<\/tag>
but such way it doesn't allow to match .*
except </tag>
before ABC
. 但是这样一来, 除了
</tag>
在ABC
之前,不允许匹配.*
。 How can I implement this? 我该如何实施?
Useful links: 有用的链接:
Since you're using one of Perl / PCRE, the fastest way to do it is like this: 由于您使用的是Perl / PCRE,因此最快的方法是这样的:
/(?s)<tag>(?:<\\/tag>(*SKIP)(*FAIL)|.)*?ABC.*?<\\/tag>/
https://regex101.com/r/AoiwIH/1 https://regex101.com/r/AoiwIH/1
Expanded 扩展
(?s)
<tag>
(?:
</tag>
(*SKIP) (*FAIL)
|
.
)*?
ABC
.*?
</tag>
Benchmark compare with the assertion method 基准与断言方法的比较
Regex1: (?s)<tag>(?:</tag>(*SKIP)(*FAIL)|.)*?ABC.*?</tag>
Completed iterations: 50 / 50 ( x 1000 )
Matches found per iteration: 1
Elapsed Time: 0.25 s, 254.91 ms, 254905 µs
Matches per sec: 196,151
Regex2: (?s)<tag>(?:(?!</tag>).)*?ABC.*?</tag>
Completed iterations: 50 / 50 ( x 1000 )
Matches found per iteration: 1
Elapsed Time: 0.33 s, 329.10 ms, 329095 µs
Matches per sec: 151,931
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.