regexregex-negation

How to negate the whole regex?


I have a regex, for example (ma|(t){1}). It matches ma and t and doesn't match bla.

I want to negate the regex, thus it must match bla and not ma and t, by adding something to this regex. I know I can write bla, the actual regex is however more complex.


Solution

  • Use negative lookaround: (?!pattern)

    Positive lookarounds can be used to assert that a pattern matches. Negative lookarounds is the opposite: it's used to assert that a pattern DOES NOT match. Some flavor supports assertions; some puts limitations on lookbehind, etc.

    Links to regular-expressions.info

    See also

    More examples

    These are attempts to come up with regex solutions to toy problems as exercises; they should be educational if you're trying to learn the various ways you can use lookarounds (nesting them, using them to capture, etc):