我需要一个正则表达式(用于输入验证),过滤掉除“下划线”之外的所有特殊字符,因此允许范围[a-zA-Z0-9 \ underscore]中的所有字符,并且可以多次出现。但在我的表达中,我不能连续出现2次“下划线”,而且我的字符串也不能以“_”开头。
答案 0 :(得分:1)
我认为你想使用groups以便repetitions正常工作:
/[A-Za-z0-9]+(?:_(?:[A-Za-z0-9]+|$))*/
答案 1 :(得分:0)
有时您会发现将您的逻辑发现转换为任何问题,而不是确保没有问题 - 产生更简单的解决方案:
// starts with underscore
// or has two underscores in a row
// or has a character other than alpha/numeric/underscore
var bad = /^_|_{2}|\W/;
if (bad.test(input)) myInputIsIllegal();
答案 2 :(得分:0)
/^([a-zA-Z0-9]_?)+$/
一个或多个...字母数字字符,可选地后跟单个下划线