Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - extract date from string using regex- failing

Tags:

java

date

regex

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...

like image 773
DasDas Avatar asked Sep 03 '13 11:09

DasDas


People also ask

What does \\ mean in Java regex?

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.

How do you check if a string matches a regex in Java?

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).

Does regex work in Java?

Java does not have a built-in Regular Expression class, but we can import the java. util. regex package to work with regular expressions.


1 Answers

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

Regular expression visualization

Diagram by Debuggex.

like image 159
sp00m Avatar answered Oct 10 '22 04:10

sp00m