如何编写正则表达式来验证逗号分隔的值列表 [英] How to write regex to verify a comma delimited list of values
问题描述
我正在使用 SobiPro,这是 joomla 的一个目录系统,我有一个字段,该字段的值仅包含字母数字和连字符,因此该文本字段中可能包含的内容示例如下:
I am using SobiPro, a directory system for joomla and I have a field that will have values that contain alphanumerics and hyphens only, so a sample of what might be in this text field would be:
玩具风筝、塑料轮、单向小玩意、金属线轴、3M 扎带
Toy Kites, Plastic Wheels, 1-Way Gizmos, Metal Spools, 3M Wire Ties
此正则表达式将在字段保存之前验证他们在表单上输入的内容.
This regex would validate what they enter on the form prior to a field save.
我是这么想的:(\w+)(,\s*\w+)*
I thought this: (\w+)(,\s*\w+)*
但显然我是不对的,它没有解释连字符..有什么帮助!谢谢!
But clearly I am not right, and it does not account for the hyphens.. any help! thanks!
推荐答案
试试这个:
^[-\w\s]+(?:,[-\w\s]*)*$
使用 ^
和 $
确保我们验证整个值,而不只是在其中的某处找到匹配项.
Using ^
and $
ensures that we validate the entire value, and don't just find a match somewhere within.
第一个字符类 [-\w\s]+
允许一个或多个字母数字、空格或破折号字符.破折号应该放在类括号中.
The first character class, [-\w\s]+
allows one or more alphanumeric, whitespace, or dash characters. The dash should go first in the class brackets.
第二组允许使用分隔逗号进行零次或多次重复.它被包裹在非捕获括号中,一个小的性能优化:(?: ... )*
The second group allows zero or more repetitions with separating commas. It is wrapped in non-capturing parentheses, a small performance optimization: (?: … )*
注意事项:
- 此表达式允许空条目,例如
A,B,,D
.如果您不想允许这样做,请将倒数第二个*
更改为+
. \w
速记允许使用下划线.为防止出现这种情况,请将它们替换为A-Za-z0-9
.
- This expression allows empty entries, such as
A,B,,D
. If you don't want to allow this, change the second-to-last*
to a+
. - The
\w
shorthand allows underscores. To prevent this, replace them withA-Za-z0-9
.
这篇关于如何编写正则表达式来验证逗号分隔的值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!