简体   繁体   English

正则表达式只允许大括号内的字母数字字符和下划线和特定占位符

[英]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. [^-A-Za-z0-9_] - 不允许使用除 az 0-9 和下划线之外的任何其他字符。

|^\\{placeholder\\} - Or anything that doesn't say {placeholder} |^\\{placeholder\\} - 或者任何没有说 {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, _ [A-Za-z0-9_] - 一个字字符:字母、数字、 _
    • | - or - 或者
    • {placeholder} - a specific substring {placeholder} - 一个特定的子字符串
  • )+ - end of group, repeat 1 or more times )+ - 组结束,重复 1 次或多次
  • $ - end of string. $ - 字符串的结尾。

See the regex demo and a Regulex graph :请参阅正则表达式演示正则表达式

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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