Narendra Chitrakar
Narendra Chitrakar

Reputation: 185

Regex to match three words separated by two commas

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.

Upvotes: 6

Views: 10726

Answers (5)

las
las

Reputation: 196

This will solve your problem, try this

([a-zA-Z0-9],[a-zA-Z0-9],([a-zA-Z0-9]))

Upvotes: -1

Alex Z
Alex Z

Reputation: 1867

Few general suggestions from performance perspective:

  1. Don't use [ ]|[ ] clause - you can just put few character classes inside one [ ], e.g. [A-Za-z0-9]
  2. Don't overuse () - usually each of them stores captured argument which requires additional overhead. If you just need to group few pieces together look for grouping operator that does not store match (it might be something like (?: ... ) )

Upvotes: 0

Tarion
Tarion

Reputation: 17134

Try this one:

([a-zA-Z0-9]+)(,[a-zA-Z0-9]+){2,}

Upvotes: 0

Neil
Neil

Reputation: 5782

/^(?:\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.

Upvotes: 5

Yuval
Yuval

Reputation: 3433

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

Upvotes: 2

Related Questions