Search code examples
regexfindstr

Regex - how to match everything except a particular pattern


How do I write a regex to match any string that doesn't meet a particular pattern? I'm faced with a situation where I have to match an (A and ~B) pattern.


Solution

  • You could use a look-ahead assertion:

    (?!999)\d{3}
    

    This example matches three digits other than 999.


    But if you happen not to have a regular expression implementation with this feature (see Comparison of Regular Expression Flavors), you probably have to build a regular expression with the basic features on your own.

    A compatible regular expression with basic syntax only would be:

    [0-8]\d\d|\d[0-8]\d|\d\d[0-8]
    

    This does also match any three digits sequence that is not 999.