Regex to highlight invalid tokens

239 views Asked by At

Hi have a field were the user can enter a string with a limited set of tokens, say {token1}, {token2}. Token is a string between curly braces, no spaces allowed.

I want to have the entry of the user checked with regex to invalidate when the user enters any unknown/invalid token. Note that the user can as well not enter a token at all.

Valid entries:

  • qwert yuiop
  • qwert{token1}yuiop
  • qwert{token1}{token2}yuiop
  • qwert {token1} {token2} yuiop

Invalid entries:

  • qwert {badtoken} yuiop
  • qwert { badtoken} yuiop
  • qwert {badtoken } yuiop
  • qwert { token1} yuiop
  • qwert {token1 } yuiop
  • qwert { token1 } yuiop
  • qwert {badtoken} {token1} yuiop

Intention-wise, the message to the user will say:

The entry contains unknown tokens. Only {token1} and {token2} are allowed.

1

There are 1 answers

4
Alan Moore On BEST ANSWER

I think this is what you're looking for:

\{(?!token[12]\}).*?\}

The part that most people don't think of in cases like this is including the ending brace (\}) in the negative lookahead, to prevent matching things like {token1 } or {token2xxxx}.

Of course, this doesn't detect tokens with missing braces, like {token1 or token2}. That would be a lot more complicated.

This regex will work in any flavor that supports lookaheads and reluctant quantifiers. Here's a demo.

Update: Per the request in a comment, here's a spelled-out version (as you would use for token names that can't be easily condensed):

\{(?!(?:token1|token2)\}).*?\}

...and an updated demo.