Nacht
Nacht

Reputation: 11366

Can someone tell me what Regex would match this?

I'm trying to make a regex that would match this string:

asf, Algeria, Wilaya d' El Tarf,

So pretty much: (word-with-characters){,}{space} and repeat 3 times (no more, no less).

I tried this:

 ^([\w ']+[,]?){3}$

But I can't seem to get the "no more, no less part" (this just matches anything with words, separated by commas and spaces, like "asf, Algeria").

I'm very new to Regex so sorry for my noobness.

Thanks.

Upvotes: 1

Views: 79

Answers (1)

NPE
NPE

Reputation: 500733

You have to make the comma mandatory:

^([\w ']+,){3}$

Otherwise "asf, Algeria" can be split into exactly three matching groups like so:

  1. "asf,"
  2. " Algeri"
  3. "a"

Making the comma mandatory closes that loophole.

Upvotes: 3

Related Questions