Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match three words separated by two commas

Tags:

regex

I am trying to get at least three words separated by two commas.I have so far managed to match two words with one comma with

/([A-z]|[0-9])(,{1})([A-z]|[0-9])/ 

but how can I add a comma and a word to this.I have tried repeating the same but did not work.

like image 831
Narendra Chitrakar Avatar asked Apr 04 '12 08:04

Narendra Chitrakar


People also ask

How do you use commas in RegEx?

The 0-9 indicates characters 0 through 9, the comma , indicates comma, and the semicolon indicates a ; . The closing ] indicates the end of the character set. The plus + indicates that one or more of the "previous item" must be present.

How do you match a semicolon in RegEx?

Semicolon is not in RegEx standard escape characters. It can be used normally in regular expressions, but it has a different function in HES so it cannot be used in expressions. As a workaround, use the regular expression standard of ASCII.

What does the plus character [+] do in RegEx?

Inside a character class, the + char is treated as a literal char, in every regex flavor. [+] always matches a single + literal char. E.g. in c#, Regex. Replace("1+2=3", @"[+]", "-") will result in 1-2=3 .


2 Answers

/^(?:\w+,){2,}(?:\w+)$/

This will get you a comma separated list of at least 3 words ([a-zA-Z0-9_]+).

/^\s*(?:\w+\s*,\s*){2,}(?:\w+\s*)$/

This is a slightly more user-friendly version of the first, allowing spaces in between words.

like image 111
Neil Avatar answered Oct 07 '22 17:10

Neil


If it's a PERL derived regex, as most implementations I've encountered, /[^,]+(?:,[^,]+){2,}/ tests well against anything that has at least two commas in it, providing that the commas have something between them. The (?:) construct allows to group without capturing. The {2,} construct specifies 2 or more matches of the previous group. In javascript, you can test it:

/[^,]+(?:,[^,]+){2,}/.test("hello,world,whats,up,next"); // returns true

/[^,]+(?:,[^,]+){2,}/.test("hello,world"); // returns false
like image 23
Yuval Avatar answered Oct 07 '22 18:10

Yuval