How can I get a regular expression that matches any string that has two or more commas?
I guess this is better explained with an example of what should match and what shouldn't
abcd,ef // Nop
abc,de,fg // Yup
// This is what I have so far, but it only matches consecutive commas
var patt = /\,{2,}/;
I'm not so good with regex and i couldn't find anything useful. Any help is appreciated.
How can I get a regular expression that matches any string that has two or more commas?
I guess this is better explained with an example of what should match and what shouldn't
abcd,ef // Nop
abc,de,fg // Yup
// This is what I have so far, but it only matches consecutive commas
var patt = /\,{2,}/;
I'm not so good with regex and i couldn't find anything useful. Any help is appreciated.
Share Improve this question edited Feb 13, 2012 at 5:11 elclanrs asked Feb 13, 2012 at 5:05 elclanrselclanrs 94.1k21 gold badges136 silver badges171 bronze badges 2- Are you saying you don't want consecutive colons to match? (Or just that that is all you've managed to match so far?) Your examples don't cover it either way. And are you looking for colons (:) or commas (,)? – nnnnnn Commented Feb 13, 2012 at 5:10
- Oh commas, typo. I'm looking to match any string that has two or more commas no matter where they are. – elclanrs Commented Feb 13, 2012 at 5:13
2 Answers
Reset to default 15This will match a string with at least 2 commas (not colons):
/,[^,]*,/
That simply says "match a comma, followed by any number of non-comma characters, followed by another comma." You could also do this:
/,.*?,/
.*?
is like .*
, but it matches as few characters as possible rather than as many as possible. That's called a "reluctant" qualifier. (I hope regexps in your language of choice support them!)
Someone suggested /,.*,/
. That's a very poor idea, because it will always run over the entire string, rather than stopping at the first 2 commas found. if the string is huge, that could be very slow.
if you want to get count of commas in a given string, just use /,/g , and get the match length
'a,b,c'.match(/,/g); //[',',','] length equals 2<br/>
'a,b'.match(/,/g); //[','] length equals 1<br/>
'ab'.match(/,/g) //result is null