Extract date with Regex

Asked

Viewed 681 times

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 pick up the first date of this example "12/02/1998".

I tried that, but it didn’t work:

^(\\d{2}\\/\\d{2}\\/\\d{4})
  • Only complementing, if the String contains only valid dates, regex resolves, but if it has things like 31/04/2018 (April 31, which is an invalid date), regex will give a false positive. I suggest that after the date is obtained from String, it is also validated using the Java date Apis as explained in this answer: https://answall.com/a/187296/112052

3 answers

5


The character ^ means beginning of string, that is, your string would have to start with the specified pattern.

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

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
}

https://ideone.com/RoKEGH

  • Thank you very much!

3

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

To the String in question the ideal is to give a match on the first occurrence of a date without any modifier like the g which is global, see the example below:

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

Example in Regex101

  • How could I check with regex if this string contains numbers ?

  • Thank you very much!

-2

Your regex will only work if the date is at the beginning of the string, try to get the " " out of the front.

  • Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.