简体   繁体   中英

Java regex matches method returning false

I'm trying to make a regex to detect if there's a date in a string, no matter if it's:

  • DD/MM/YYYY
  • DD/MM/YY
  • MM/DD/YYYY
  • MM/DD/YY
  • YYYY/MM/DD
  • YY/MM/DD

I tried to test it in a class using Pattern.matches() but it returns false even though I have some dates in my string and regex101 seems to say that my regex is correct.

Here's the code with which I tested:

import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) {
        String line = "31/07/12;401000;02/04/2013;400;";
        System.out.println(Pattern.compile("\\d{2,4}/\\d{2}/\\d{2,4}").matcher(line).matches());
    }
}

I was wondering if maybe it was an option problem but I can't find anything that'd go in that direction. What can I do to make it return true ?

Try it like this. Check and see if the matcher can find any match and then print out the group that matches.

String line = "31/07/12;401000;02/04/2013;400;";
Matcher m = Pattern.compile("\\d{2,4}/\\d{2}/\\d{2,4}").matcher(line);
while (m.find()) {
    System.out.println(m.group());
}

prints

31/07/12
02/04/2013

Note that your regex may also match incorrectly specified dates. For example both day and month can't both be four digits at the same time. You would be better off having multiple patterns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM