I'm trying to extract 2 dates from a string using regex- and for some reason - the regex doesn't extract dates- this is my code:
private String[] getDate(String desc) {
int count=0;
String[] allMatches = new String[2];
Matcher m = Pattern.compile("(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d(?:,)").matcher(desc);
while (m.find()) {
allMatches[count] = m.group();
}
return allMatches;
}
My string- desc is: "coming from the 11/25/2009 to the 11/30/2009"
and I get back a null array...
The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.
Variant 1: String matches() This method tells whether or not this string matches the given regular expression. An invocation of this method of the form str. matches(regex) yields exactly the same result as the expression Pattern. matches(regex, str).
Java does not have a built-in Regular Expression class, but we can import the java. util. regex package to work with regular expressions.
Your regex matches day first and then month (DD/MM/YYYY), while your inputs start with month and then day (MM/DD/YYYY).
Moreover, your dates must be followed by a comma to be matched (the (?:,)
part).
This one should suit your needs:
(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d
Diagram by Debuggex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With