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

问题描述 投票:1回答:1

我想要一个正则表达式,只允许使用字母数字字符和下划线以及花括号内的特定占位符。

有效示例:

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

这就是我想出的:

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

我理解这个的方式是:

[^-A-Za-z0-9_] - 不允许任何其他字符而不是a-z 0-9和下划线。

|^\{placeholder\} - 或任何不说{placeholder}的东西

但它不起作用,我不知道为什么。

这是demo

请帮忙。

php regex pcre
1个回答
1
投票

您可以使用

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

细节

  • ^ - 字符串的开头
  • (?: - 非捕获组的开始: [A-Za-z0-9_] - 字char:字母,数字,_ | - 或 {placeholder} - 一个特定的子串
  • )+ - 组结束,重复1次或更多次
  • $ - 字符串的结尾。

查看regex demoRegulex graph

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.