Mitchell Gharechedaghi Mitchell Gharechedaghi - 7 months ago 12
Java Question

What is the regex for finding a particular format of a piece of text

What is the regex for finding if a piece of text is in a particulate format?

Format should follow:

AAAA-123
or
AAAA123
(with or without the dash)

Where the first 4 characters are letters in the range A-M and the following 3 characters are numbers with a max of 299.

Example:

ABCD-299
would match

and

ABZR-301
would not match

Answer
[A-M]{4}-?[0-2][0-9]{2}

Basically:
[A-M]{4} = 4 of any letters A-M
-? = an optional dash
[0-2] = a single 0,1, or 2
[0-9]{2} = two of any number

limiting the first number to 0-2 effectively limits your number to 299, and allows for 000-299

i'm not sure if you are searching for this in a string or checking that a string equals exactly this... and that context might change how you use the above. for example, if you are testing a string you'll want to wrap it with ^ and $

Comments