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

后端 未结 2 612
忘了有多久
忘了有多久 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:08

    Do you really require this in a single regex? If not, then the simplest implementation is just two regexes - one to check you don't match one of your forbidden words, and one to match your \w+, chained with a logical AND.

    0 讨论(0)
  • 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+\((?<!\b(?:cat|dog|sheep)\()
      

    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.

    0 讨论(0)
提交回复
热议问题