Tim Tim - 4 months ago 9
Java Question

Java - Regex - Months requiring 1-12

I'm trying to build a regex for a field containing the number of months, of course, this needs to be only numbers 1-12. However, new to regex this is a bit new to me and I just need to check I'm right. It seems to work alright. Although, am I correct in assuming the range here 1-12 allows any number in this range, I only ask as I've only ever seen it done with 0-9 before.

[1-12]{1,2}

Answer

This might do. Two digits or one digit

1[0-2]|[1-9]

Edit: If you're worried about numbers like 55 use this:

^(1[0-2]|[1-9])$

Adding the ^ and $ means start and end of string. Use https://regex101.com as a good learning tool.