Home > Software engineering >  use regex to check that start of user input has exactly two curly brackets
use regex to check that start of user input has exactly two curly brackets

Time:10-05

I'm trying to make sure that user input is exactly {{user_input}} in regards to the brackets. text can be anything as long as it's a number or character. {{(.*?)}} works to make sure that the two brackets exist at the beginning and end of the input but I also want to make sure there are only two brackets. I've tried [^{]{{(.*?)}}[^}] and {{2}(.*?)}{2}, but it still counts {{{user_input}} as valid.

CodePudding user response:

Use

/^{{([^{}]*?)}}$/

to exclude curly braces in the middle of user input.

CodePudding user response:

(?<![{])a => There must not "{" character before the "a"

a(?![}]) => There must not "}" character after the "a"

a([^{}]*)a => All characters except "{" and "}" between "a"s

Solution:

(?<![{]){{([^{}]*?)}}(?![}])

Sample: https://regex101.com/r/OiLk8S/1

  • Related