3

I need to check input with preg_match, which must be of this format: xxx.xxx.xxx The number of block can vary... These are all examples of valid inputs:

001
00a.00a
0fg.001
aaa.aaa.001
001.001.002.001.001.001

Well I could probably write a regexp something like:

^([\da-z]{3}\.?)+$

But here comes the problem with the quantifier of the period. I mean if I use '?' to match 0 or 1 times, it would also match even if skip the dots somewhere, eg:

000.001.0010az001

then, if I used {1} to match one time, it would match nothing, because the last block does not have a dot.

So I can't think what to think of... Please advice

Anonymous
  • 4,692
  • 8
  • 61
  • 91

2 Answers2

4

You can use:

^[\da-z]{3}(?:\.[\da-z]{3})*$
codaddict
  • 445,704
  • 82
  • 492
  • 529
0
/^(?:[\da-z]{3}\.)*[\da-z]{3}$/
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks for quick replies all! but I just wonder why would we need '?:', wound't it work without it?... – Anonymous Jul 11 '12 at 11:25
  • Yes, that's just a [non-matching group](http://stackoverflow.com/questions/3512471/non-capturing-group). – Bergi Jul 11 '12 at 11:27
  • Hmmm, I'm confused... Could you just give me some hint about it? ;P – Anonymous Jul 11 '12 at 11:28
  • Oh, thanks, thats a huge one, gotta study it then. :) I shall accept as the answer then because you actually explained it. I shall also upvote the answer of codaddict ;) – Anonymous Jul 11 '12 at 11:32