Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

validation - 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:

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.

I thought this: (w+)(,s*w+)*

But clearly I am not right, and it does not account for the hyphens.. any help! thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

^[-ws]+(?:,[-ws]*)*$

Using ^ and $ ensures that we validate the entire value, and don't just find a match somewhere within.

The first character class, [-ws]+ 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: (?: … )*

Notes:

  • 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 with A-Za-z0-9.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...