简体   繁体   English

正则表达式匹配什么不匹配

[英]Regex match what did not match

In words, I would describe the problem as "match A or B , match foo , and then match A or B that did NOT match previously". 换句话说,我会将问题描述为“匹配AB ,匹配foo ,然后匹配之前不匹配的AB ”。

I can do it with the following regex: 我可以使用以下正则表达式:

AfooB|BfooA

I'm wondering if there is a more efficient way to do this? 我想知道是否有更有效的方法来做到这一点? I know how to reference a captured group using the "\\" and then the group number. 我知道如何使用"\\"引用捕获的组,然后使用组号。 In this case I would like to apply something like to say "not the option that matched in the captured group" (and still be restricted to only match the other possible matches for that group). 在这种情况下,我想应用类似的说“不是在捕获的组中匹配的选项”(并且仍然仅限于匹配该组的其他可能的匹配)。

The reason I'm looking for something more efficient than simply "AfooB|BfooA" is that in my case "foo" is a very long pattern and I would prefer to reduce duplication if possible. 我正在寻找比简单的"AfooB|BfooA"更高效的东西的原因是,在我的情况下, "foo"是一个非常长的模式,如果可能的话我宁愿减少重复。

You may use a negative lookahead with a backreference restriction when matching the second A or B : 匹配第二个AB时,您可以使用具有反向引用限制的负前瞻:

(A|B)foo(?!\1)(A|B)

Basically, (A|B) matches and captures the value into Group 1, then foo matches foo , (?!\\1) makes sure that the text that follows is not the same as the one captured into the first group, and then it can only match the opposite value with (A|B) . 基本上, (A|B)匹配并将捕获到组1中,然后foo匹配foo(?!\\1)确保后面的文本与捕获到第一组中的文本不同,然后它只能将相反的值与(A|B)匹配。

See this regex demo 看到这个正则表达式演示

NOTE: if A and B are single characters, use a character class: ([AB])foo(?!\\1)([AB]) 注意:如果AB是单个字符,请使用字符类: ([AB])foo(?!\\1)([AB])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM