用逗号或逗号和空格分隔的项目列表的正则表达式 [英] Regular expression for a list of items separated by comma or by comma and a space
问题描述
嘿,我不知道如何为我的网站编写正则表达式,我想让用户输入以逗号或逗号和空格分隔的项目(标签)列表,例如apple, pie,applepie".有可能有这样的正则表达式吗?谢谢!
Hey, I can't figure out how to write a regular expression for my website, I would like to let the user input a list of items (tags) separated by comma or by comma and a space, for example "apple, pie,applepie". Would it be possible to have such regexp? Thanks!
我想要一个 javascript 的正则表达式,以便在用户提交表单之前检查输入.
I would like a regexp for javascript in order to check the input before the user submits a form.
推荐答案
您要寻找的东西看似简单:
What you're looking for is deceptively easy:
[^,]+
这将为您提供每个逗号分隔的标记,并将排除空标记(如果用户输入a,,b",您将只会得到a"和b"),但如果他们输入"a, , b".
This will give you every comma-separated token, and will exclude empty tokens (if the user enters "a,,b" you will only get 'a' and 'b'), BUT it will break if they enter "a, ,b".
如果你想从两边正确地去除空格(并排除只有空格的元素),那么它会变得稍微复杂一点:
If you want to strip the spaces from either side properly (and exclude whitespace only elements), then it gets a tiny bit more complicated:
[^,\s][^\,]*[^,\s]*
然而,正如一些评论中提到的,为什么你需要一个正则表达式,其中一个简单的拆分和修剪就可以解决问题?
However, as has been mentioned in some of the comments, why do you need a regex where a simple split and trim will do the trick?
这篇关于用逗号或逗号和空格分隔的项目列表的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!