RegEx match two or more same character non-consecutive

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.

Answers:

Answer

This 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.

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.