Extract date with Regex

4

I'm trying to extract a date from a String, but I'm not getting it.

Example:

String stringQualquer = "um teste qualquer12/02/1998 19/09/1880 Nulo";

I want to get the first date of this example "12/02/1998".

I tried that, but it did not work:

^(\d{2}\/\d{2}\/\d{4})
    
asked by anonymous 02.08.2018 / 21:35

3 answers

5

The character ^ means string start, meaning your string would have to start with the given pattern.

Only (\d{2}\/\d{2}\/\d{4}) is sufficient.

To get the first one, just do not advance the matcher:

String stringQualquer = "um teste qualquer12/02/1998 19/09/1880 Nulo";

Pattern pattern = Pattern.compile("(\d{2}/\d{2}/\d{4})");

Matcher matcher = pattern.matcher(stringQualquer);

if(matcher.find()) {
  System.out.println(matcher.group()); // printa 12/02/1998
}

link

    
02.08.2018 / 21:57
3

Your regex is correct, but ^ is an anchor and indicates that you will perform the match at the beginning of String .

For the String in question the ideal is to match the first occurrence of a date with no modifier like the g that is global, see the example below:

(\d{2}\/\d{2}\/\d{4})

Example on Regex101

    
02.08.2018 / 22:02
-2

Your regex will only work if the date is at the beginning of the string, try to take the "^" from the front.

    
02.08.2018 / 21:56