如何为包含字母数字和特殊字符的输入编写匹配项

时间:2012-03-09 02:06:34

标签: regex grails groovy

我的matches有问题。我有一个字段,应该接受一个可能包含alphanumeric and special characters的任意组合的值。我有一个代码在输入为1) combination of alphanumeric and special characters, and 2) alphanumeric时工作正常。但如果输入包含1) number and special characters ONLY without alphabet or 2) alphabet and special characters ONLY without number的组合,我的matches出错了。我想要做的是创建一个最适用于以下输入组合的matches

1) alphabet+number
2) alphabet+special character
3) alphabet+number+special character
4) number+special character

这是我的代码:

matches: /^(?=.*[0-9]+.*)(?=.*[a-zA-Z]+.*)[0-9a-zA-Z_\[\]\\\^\$\.\|\?\*\+\(\)~!@#%&-=]{8,}$/

我需要你的建议! 谢谢!

2 个答案:

答案 0 :(得分:1)

这是因为您的积极前瞻要求两个 [0-9]出现出现[a-zA-Z]

尝试将此缩减为单个前瞻,这只是指定至少有一个<{em> [0-9][a-zA-Z]存在:

matches: /^(?=.*[0-9a-zA-Z])[0-9a-zA-Z_\[\]\\\^\$\.\|\?\*\+\(\)~!@#%&-=]{8,}$/

此外,您可以通过将前瞻中的.*修改为[^0-9a-zA-Z]*来提高正则表达式的效率:前瞻与先发条件匹配的第一个字母数字然后停止,防止不必要的扫描:

matches: /^(?=[^0-9a-zA-Z]*[0-9a-zA-Z])[0-9a-zA-Z_\[\]\\\^\$\.\|\?\*\+\(\)~!@#%&-=]{8,}$/

答案 1 :(得分:0)

 /^(?=.*[a-zA-Z0-9]+.*)[_\[\]\\\^\$\.\|\?\*\+\(\)~!@#%&-=]{8,}$/