Regular expression to match simple "id" values?
I need regex fo开发者_开发技巧r 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:
- AB125
- AC123-25
- BT1-2535
Seems simple , but I got stuck with it ...
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.
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.
精彩评论