正则表达式匹配单词

时间:2019-07-01 15:00:01

标签: regex perl pcre regex-lookarounds regex-negation

所有有关 匹配除单词 以外的内容的质量检查的信息,我发现这暗示着行的开头/结尾(^ $)。但是我想不出如何匹配所有字符(像.*这样的任何字符),除了已处理文本中间的其他单词之前的单词。

我应该在ABC中匹配<tag></tag>

...<tag>a a.__aABC&*</tag>aaa<tag>ffff</tag>...

但不在外面(假阳性):

...<tag>a a.__a&*</tag>ABC<tag>ffff</tag>...

因此,我认为我应该在</tag>之前排除标签关闭(ABC)。 我尝试过:

<tag>(?!<\/tag>)ABC.*?<\/tag>

但是以这种方式不允许 匹配.*,除了</tag>之前的ABC 。我该如何实施?

有用的链接:

12

1 个答案:

答案 0 :(得分:2)

由于您使用的是Perl / PCRE,因此最快的方法是这样的:

/(?s)<tag>(?:<\/tag>(*SKIP)(*FAIL)|.)*?ABC.*?<\/tag>/

https://regex101.com/r/AoiwIH/1

扩展

 (?s)
 <tag>  
 (?:
      </tag>
      (*SKIP) (*FAIL) 
   |  
      . 
 )*?
 ABC
 .*? 
 </tag>

基准与 asserttion 方法

进行比较
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