-1

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)

Community
  • 1
  • 1
felwithe
  • 2,683
  • 2
  • 23
  • 38

2 Answers2

4

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 notnotthis`
  • .* 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

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • No; I want `this` to be followed by anything except `notthis`. (I don't mean directly followed; I mean anywhere in the string.) You answer will still match `thistestnotthis`. – felwithe Apr 27 '19 at 15:01
  • @felwithe Ok, I have updated the answer. You could use `^this(?!.*notthis).*$` – The fourth bird Apr 27 '19 at 15:02
  • Ok. So the problem is that I need to use the quantifier twice-- once inside the negative lookahead, and once outside of it. I was trying to do it using a quantifier just once. – felwithe Apr 27 '19 at 15:04
  • 1
    The lookahead does the assertion to check if what is on the right side does not contain notthis. The lookahead is an assertion which does not consume any characters so you still have to do the matching using `.*` – The fourth bird Apr 27 '19 at 15:06
0

Because of the order of your rules. Before your expression would get to negative lookahead, prior rules has been fulfilled, there is nothing left to match.

If you wish to match everything after this, except for notthis, this RegEx might also help you to do so:

^this([\s\S]*?)(notthis|())$

which creates an empty group () for nothing, with an OR to ignore notthis:

^this([\s\S]*?)(notthis|())$

enter image description here

You might remove (), ^ and $, and it may still work:

this([\s\S]*?)(notthis|)
Emma
  • 27,428
  • 11
  • 44
  • 69
  • 2
    Your regex matches strings even if there is `notthis`. They don't want to match such strings. – Toto Apr 27 '19 at 15:24