Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 860
elclanrs Avatar asked Feb 13 '12 05:02

elclanrs


Video Answer


2 Answers

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.

like image 107
Alex D Avatar answered Oct 07 '22 02:10

Alex D


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
like image 24
chameleon Avatar answered Oct 07 '22 01:10

chameleon