rsturim
rsturim

Reputation: 6846

If paired braces present, only allow specific strings regex

I'm trying to validate user inputed tokens.

My rule is, if the user enters a string between dual braces, {{myToken}} then only specific words will be allow to be placed between them. For this example, let's say "dog" and "cat" are valid, but invalid for anything other strings inside the braces. If no braces are present, then any strings are allowed.

I've found writing the a simple to detect dog or cat is quite easy.

test sentence 1:

/{{(dog|cat+?)}}/g

But, I still want this sentence to be valid as well:

test sentence 2:

And finally, this sentence should be invalid:

test sentence 3:

Upvotes: 1

Views: 58

Answers (1)

ctwheels
ctwheels

Reputation: 22817

It's not clear what you're trying to match, but I'm assuming it's the whole string if the following rules are followed:

  • Contains no double curly brackets: {{...}}

    I own a fish

  • Contains one or more double curly brackets with the following contents: {{dog}} {{cat}}

    I own a {{dog}} and {{cat}} but not fish

Anything that isn't matched by the above should be considered invalid:

I own a {{cow}}


There are several ways of matching those strings.

Method 1 - Tempered Greedy Token

You can extend the tempered greedy token with an alternation to match the specified double curly brackets:

See regex in use here

^(?:(?!{{2}).|{{2}(?:dog|cat)}{2})+$

How it works:

  • ^ assert position at the start of the line
  • (?:(?!{{2}).|{{2}(?:dog|cat)}{2})+ tempered greedy token matching the following one or more times
    • (?!{{2}). negative lookahead ensuring what follows is not {{, and if it isn't, match the character (. matches anything except newline characters - if you need to match newline characters, change . to [\s\S] or enable the s modifier)
    • {{2}(?:dog|cat)}{2} matches {{dog}} or {{cat}}
  • $ assert position at the end of the line

Method 2 - Simple alternation

You can use a fairly simple alternation to replace what the tempered greedy token does above:

See regex in use here: (note the link has \n in the first character set for display purposes)

^(?:[^{]|{(?!{)|{{2}(?:dog|cat)}{2})+$

How it works:

  • ^ assert position at the start of the line
  • (?:[^{]|{(?!{)|{{2}(?:dog|cat)}{2})+ match the following one more times
    • [^{] match any character except {
    • {(?!{) match { if it's not followed by { (for example, if you had something like {this} - it would allow it to match)
    • {{2}(?:dog|cat)}{2} matches {{dog}} or {{cat}}
  • $ assert position at the end of the line

Upvotes: 3

Related Questions