简体   繁体   中英

Java - Regex extract date from string

I need to extract date from this string:

BB inform: buy your tickect, final card number xxxx, $ 00,00, on 04/10, at 11:28. If you don't recognize call 40032 2412.

Also The full date 04/10/2015

The date pattern is dd/MM or dd/MM/yyyy

The code:

String mydata = "BB inform: buy your tickect, final card number xxxx, $ 00,00, on 04/10, at 11:28. If you don't recognize call 40032 2412.";

    Pattern p = Pattern.compile("(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\\d\\d");
    Matcher m = p.matcher(mydata);

Result: m.matches() == false

You can try with this regex :

Matcher m = Pattern.compile("(\\d{1,2}/\\d{1,2}/\\d{4}|\\d{1,2}/\\d{1,2})", Pattern.CASE_INSENSITIVE).matcher(string);
        while (m.find()) {
            System.out.println(m.group(1));
        }

Its looking for a pattern DD/MM or then looking for a DD/MM/YYYY.

Check this Link

Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE); 
  Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));

        }

Pattern.MULTILINE ensures that it is searching the match of DD/MM or DD/MM/YYYY if it exist in the string

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