Regex to match a pattern, but exclude a set of words

后端 未结 2 619
忘了有多久
忘了有多久 2020-12-30 04:27

I have been looking through SO and although this question has been answered in one scenario:

Regex to match all words except a given list

It\'s not quite wha

2条回答
  •  独厮守ぢ
    2020-12-30 05:26

    If the regular expression implementation supports look-ahead or look-behind assertions, you could use the following:

    • Using a negative look-ahead assertion:

       \b(?!(?:cat|dog|sheep)\()\w+\(
      
    • Using a negative look-behind assertion:

       \b\w+\((?

    I added the \b anchor that marks a word boundary. So catdog( would be matched although it contains dog(.

    But while look-ahead assertions are more widely supported by regex implementations, the regex with the look-behind assertion is more efficient since it’s only tested if the preceding regex (in our case \b\w+\() already did match. However the look-ahead assertion would be tested before the actual regex would match. So in our case the look-ahead assertion is tested whenever \b is matched.

提交回复
热议问题