[英]How to write regex to verify a comma delimited list of values
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: 我正在使用SobiPro,一个joomla的目录系统,我有一个字段,其值只包含字母数字和连字符,所以这个文本字段中可能包含的示例如下:
Toy Kites, Plastic Wheels, 1-Way Gizmos, Metal Spools, 3M Wire Ties 玩具风筝,塑料轮,单向小玩意,金属线轴,3M线束
This regex would validate what they enter on the form prior to a field save. 这个正则表达式将验证它们在字段保存之前在表单上输入的内容。
I thought this: (\\w+)(,\\s*\\w+)* 我想这个:(\\ w +)(,\\ s * \\ w +)*
But clearly I am not right, and it does not account for the hyphens.. any help! 但显然我不对,它没有考虑连字符..任何帮助! thanks!
谢谢!
Try this: 试试这个:
^[-\w\s]+(?:,[-\w\s]*)*$
Using ^
and $
ensures that we validate the entire value, and don't just find a match somewhere within. 使用
^
和$
可确保我们验证整个值,而不只是在其中找到匹配项。
The first character class, [-\\w\\s]+
allows one or more alphanumeric, whitespace, or dash characters. 第一个字符类
[-\\w\\s]+
允许使用一个或多个字母数字,空格或短划线字符。 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:
(?: … )*
它包含在非捕获括号中,一个小的性能优化:
(?: … )*
Notes: 笔记:
A,B,,D
. A,B,,D
。 If you don't want to allow this, change the second-to-last *
to a +
. *
更改为+
。 \\w
shorthand allows underscores. \\w
简写允许下划线。 To prevent this, replace them with A-Za-z0-9
. A-Za-z0-9
替换它们。 Try this: 试试这个:
[-\w\s]+(,[-\w\s]+)*
[-\\w\\s]
means a word character, space or hyphen. [-\\w\\s]
表示单词字符,空格或连字符。
A word character usually includes _
, so you may want to replace that with A-Za-z0-9
if you want to prevent this. 单词字符通常包含
_
,因此如果要防止这种情况,您可能希望将其替换为A-Za-z0-9
。
[-A-Za-z0-9\s]+(,[-A-Za-z0-9\s]+)*
Use character classes. 使用字符类。
^([0-9A-Za-z -]+)(,[0-9A-Za-z -]+)*$
Note that \\w
includes underscores, which is why I'm expanding it to alphanumeric ranges. 请注意
\\w
包含下划线,这就是我将其扩展到字母数字范围的原因。
Thanks to @Jay for pointing out missing anchors. 感谢@Jay指出丢失的锚点。
You can use a character class for this: 您可以使用字符类 :
[\w\s-]+(,[\w\s-]*)*
I've made the character class inside the group optional in order to allow empty fields. 我已将组内的字符类设置为可选,以允许空字段。
If your validator doesn't force the regex to always match the entire input field, you may need to anchor it by surrounding it with ^
at the start and $
at the end. 如果验证器没有强制正则表达式始终与整个输入字段匹配,则可能需要通过在开始时使用
^
并在结尾处使用$
来将其锚定 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.