M.M
M.M

Reputation: 1373

Regular expression to match simple "id" values?

I need regex for a line that starts with two characters followed by 2-4 digits or 2-4 digits followed by "-" and followed by 2-4 digits.

Examples:

Seems simple , but I got stuck with it ...

Upvotes: 1

Views: 1642

Answers (2)

paxdiablo
paxdiablo

Reputation: 882526

Regular expressions always seem simple, right up to the point where you try to use them :-)

This particular one can be done with something along the lines of:

^[A-Z]{2}([0-9]{2,4}-)?[0-9]{2,4}$

That's:

  • 2 alpha (uppercase) characters.
  • an optional 2-to-4-digit and hyphen sequence.
  • a mandatory 2-to-4-digit sequence.
  • start and end markers.

That last one, BT1-2535, doesn't match your textual specification by the way since it only has one digit before the hyphen. I'm assuming that was a typo. You will also have to change the character bit to use [A-Za-z] if you want to allow lowercase as well.

Upvotes: 4

Cameron
Cameron

Reputation: 98876

How about:

^[A-Z]{2}\d{2,4}(?:-\d{2,4})?

This matches two uppercase letters followed by 2-4 digits, followed by (optionally) a hyphen and another 2-4 digits.

Upvotes: 1

Related Questions