-2

I have a string as follows

New York, New York, United States

I need a Regular Expression ether for at least 1 comma or at least 2 comma or A any three words with 2 commas in between .

Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

1
^[^,\n]+,(?:[^,\n]+,?)*$

You can use this.Replace * by {1,2} if you want only 3 words.See demo.

^[^,\n]+,(?:[^,\n]+,?){0,2}$

https://regex101.com/r/bW3aR1/11

var re = /^[^,\n]+(?:,[^,\n]+)*$/gm;
var str = 'New York, New York, United States\nNew York, New York\nNew York\nNew York, New York, United States,';
var m;

while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
vks
  • 67,027
  • 10
  • 91
  • 124