Search code examples
phpregexpcre

Regex that will only allow alphanumeric characters and underscore and specific placeholder inside curly braces


I want a regex that will only allow alphanumeric characters and underscore and specific placeholder inside curly braces.

Valid examples:

test{placeholder}
test_{placeholder}
test_123_{placeholder}
test
test_123
test123
{placeholder}_test
test{placeholder}test
And any combination of above.

This is what I came up with:

[^-A-Za-z0-9_]|^\{placeholder\}

The way I understand this is:

[^-A-Za-z0-9_] - Don't allow any other characters than a-z 0-9 and underscore.

|^\{placeholder\} - Or anything that doesn't say {placeholder}

But it doesn't work and I am not sure why.

Here is demo

Please help.


Solution

  • You can use

    ^(?:[A-Za-z0-9_]|{placeholder})+$
    

    Details

    • ^ - start of string
    • (?: - start of a non-capturing group:
      • [A-Za-z0-9_] - a word char: letter, digit, _
      • | - or
      • {placeholder} - a specific substring
    • )+ - end of group, repeat 1 or more times
    • $ - end of string.

    See the regex demo and a Regulex graph:

    enter image description here