Reputation: 287
I am using regular expression to parse date formats from a string . It could be like
1/1/11
01/01/11
01/01/2011
01/1/2011
1/11/2011
1/11/11
11/1/11
Java code:
public static String getDateFromRemarks(String str) {
String parsedDate = null;
if (str != null) {
String regex = ".*([0-3]?[0-9]/[0-3]?[0-9]/(?:[0-9]{2})?[0-9]{2}).*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
parsedDate = matcher.group(1);
}
}
return parsedDate;
}
Input:
kjs22/12/2011 kjdflk
Output:
2/12/2011
Input:
kjs2/12/2011 kjdflk
Output:
2/12/2011
I should get date as
22/12/2011
Upvotes: 0
Views: 85
Reputation: 121712
This is because of your initial .*
. It swallows everything then backtracks.
And since the first digit is optional before your first /, the regex is satisfied with only one digit even if there are two.
Change your initial .*
to [^\d]*
.
Upvotes: 3