0

Am working on regular expression for following formats of zip in groovy

Includes a letter (L12345)
Includes a dash plus 4 more numbers (77056-1234)
Includes spaces (77056 1234)

I have this "^\d{5}(-\d{4})?\$" but its not matching the required formats. Could anyone please help me?

tim_yates
  • 167,322
  • 27
  • 342
  • 338
OTUser
  • 3,788
  • 19
  • 69
  • 127

1 Answers1

5
^\d{5}(?:[-\s]\d{4})?$
  • ^ = Start of the string.
  • \d{5} = Match 5 digits (for condition 1, 2, 3)
  • (?:…) = Grouping
  • [-\s] = Match a space (for condition 3) or a hyphen (for condition 2)
  • \d{4} = Match 4 digits (for condition 2, 3)
  • …? = The pattern before it is optional (for condition 1)
  • $ = End of the string.

This is from the following question, hope it helps

regex for zip-code

For the optiona startingil letter use

[A-Z]?

to make the letter optional. {1} is redundant. (Of course you could also write [A-Z]{0,1} which would mean the same, but that's what the ? is there for.)

I think it should go after the ^ but haven't had a chance to test

Community
  • 1
  • 1
Thomas Harris
  • 434
  • 3
  • 14
  • Thank you so much for the prompt reply, I think this expression doesn't satisfy the 1st format "L12345" – OTUser Oct 24 '13 at 21:26