简体   繁体   中英

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 az 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.

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 :

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM