Search code examples
regexpcreregex-lookarounds

RegEx for combining "match everything" and "negative lookahead"


I'm trying to match the string "this" followed by anything (any number of characters) except "notthis".

Regex: ^this.*(?!notthis)$

Matches: thisnotthis

Why?

Even its explanation in a regex calculator seems to say it should work. The explanation section says

Negative Lookahead (?!notthis)

Assert that the Regex below does not match

notthis matches the characters notthis literally (case sensitive)


Solution

  • The negative lookahead has no impact in ^this.*(?!notthis)$ because the .* will first match until the end of the string where notthis is not present any more at the end.

    I think you meant ^this(?!notthis).*$ where you match this from the start of the string and then check what is directly on the right can not be notthis

    If that is the case, then match any character except a newline until the end of the string.

    ^this(?!notthis).*$
    

    Details of the pattern

    • ^ Assert start of the string
    • this Match this literally
    • (?!notthis) Assert what is directly on the right is not notthis
    • .* Match 0+ times any char except a newline
    • $ Assert end of the string

    Regex demo

    If notthis can not be present in the string instead of directly after this you could add .* to the negative lookahead:

    ^this(?!.*notthis).*$
            ^^
    

    Regex demo

    See it in a regulex visual

    enter image description here