简体   繁体   中英

Regex match these words, but exclude matches with these

I'm looking for a regex expression to run through several strings and match these words in them:

Maces Armour Evasion Shields

Excluding strings which contain these words alongside:

Swords Axes Staves

For example (these 2 lines are one string):

12% Increased Physical Damage with Maces
8% Increased Armour

should be a match, but this one should not be (these 2 lines are also one string but it contains forbidden word "swords" with needed word "evasion"):

10% Increased Evasion
8% Increased Attack Speed with Swords

How do I exclude that list?

您可以对所需的单词使用前瞻性,对禁止的单词使用否定前瞻(如果您的正则表达式引擎允许这两个功能):

(?s)(?=.*\b(?:Maces|Armour|Evasion|Shields)\b)(?!.*\b(?:Swords|Axes|Staves)\b)^.+$

You can use a singleline regex:

/^(?=.*(?>Maces|Armour|Evasion|Shields))(?!.*(?>Swords|Axes|Staves)).+$/s
  • (?=.*(?>Maces|Armour|Evasion|Shields)) Asserts that one of these words are present in string [no backtracking]
  • (?!.*(?>Swords|Axes|Staves)) Asserts that none of these words are present in string [no backtracking]

Here is a regex demo !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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