1

I'm looking to allow the inequality operator, but disallow the special character '!' on its own.

Maybe I can use two regular expressions, /!=/ and /!/. I want to test for /!/ if it is alone - and output an error if it isn't accompanied by an equal sign. The issue is that /!/ will test true if the input is '!='. Thoughts?

Input: "!= !"

Expected Output: "Token '!=' Found

Invalid Character '!' Found

Streamer
  • 173
  • 1
  • 1
  • 11

2 Answers2

1

You need to use a negative lookahead to make sure some pattern is not found to the right of the current location:

/!(?!=)/

See the regex demo. Here, ! is only matched if there is no = immediately after it.

See more about how negative lookahead works here.

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

From what I understand you want to search for a character ! which is NOT followed by a character =. That sounds similar to this question. I tried here:

// regex (?=!(?!\=))

!= ! // matches
foo ! bar // matches
foo != bar // doesn't match

The keyword here is lookaround. See details there (and in the question I linked).

Community
  • 1
  • 1
crusy
  • 1,424
  • 2
  • 25
  • 54