Java regex month 2 digits

I only want to catch one of the following:

01 , 02 , ... , 09 , 10 , 11 , 12

      

Is the following regex complete or am I missing something?

String monthPat = "^[1][0-2]|[0][1-9]$"

      

+3


source to share


2 answers


The problem with your current regex is that when alternating, you are trying to match one of the following expressions:

^[1][0-2]     # strings that start with '10', '11', or '12'
[0][1-9]$     # strings that end with '01' through '09'

      

This means that you can have partial matches for longer strings, for example, you will match "10" at the beginning of "1000" and "09" at the end of "2009".

Make sure you include both bindings on each side |

to fix this:



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

      

Alternatively, you can alternate within the group and anchor outside:

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

      

Note that I also removed the character class (square brackets) from [1]

and [0]

, since the meaning is the same.

+9


source


From what I can see, you are checking. If you execute them using the method matches

in the class String, then binding ^

and $

do not need.

You can make it a little shorter as the character class is not needed when there is only 1 character:

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

      

The improved regular expression can be used if you use it with a method matches

in the String class, because the method matches

returns true

if the given pattern matches the entire string.

Note that your regex has a slightly different meaning when considered separately.



"^[1][0-2]|[0][1-9]$"

      

If you pass this value in Pattern.compile

, use a class Matcher.find

, this will match a substring starting 10 to 12 or ending 01 to 09, as the alternation will alternate between the two subpatterns: ^[1][0-2]

and [0][1-9]$

. Change it to

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

      

and it will only find a match if the string is exactly 01 to 12.

This knowledge is useful when writing code in other languages, because the method match

of the String / utility class that works with a regular expression can return a substring that matches the regular expression if you don't supply the anchors ^

and $

.

+1


source







All Articles