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 yuiopqwert{token1}yuiopqwert{token1}{token2}yuiopqwert {token1} {token2} yuiop
Invalid entries:
qwert {badtoken} yuiopqwert { badtoken} yuiopqwert {badtoken } yuiopqwert { token1} yuiopqwert {token1 } yuiopqwert { token1 } yuiopqwert {badtoken} {token1} yuiop
Intention-wise, the message to the user will say:
The entry contains unknown tokens. Only {token1} and {token2} are allowed.
I think this is what you're looking for:
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
{token1ortoken2}. 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):
...and an updated demo.