Newaz Sharif Amit Newaz Sharif Amit - 29 days ago 17
Java Question

Why this Regex does not works?

I have method and it accepts a date as a String and my goal is to find out the month Type as it numeric or String like 01.02....or jan, feb so i need to compare this month value to Regex but unfortunately if month field contain numeric value then match.find() not works but why? Thanks in Advance

public static String detectMonthType(String date) {
String[] parts = {};

if(date.contains("/")) {
parts = date.split("/");
} else {
parts = date.split("-");

String dateType = "";
String month = parts[1];
String strPattern = "^(0|[1-9][0-9]*)$";
Pattern pattern = Pattern.compile(strPattern);
Matcher match = pattern.matcher(month);

if(match.find()) {
return dateType = "numericMonth";
} else {
return dateType = "strMonth";


Your regexp isn't going to match a two-digit number if the first digit is zero... just like in your input. You should probably branch the regex differently as ^(0[1-9]+|1[0-2])$ which, unlike your displayed regex will exclude zero and impossible months like 13.