Regex to get a dd/MM/yyyy date by ignoring characters in the middle?

Asked

Viewed 23 times

-1

In this case I can have a string like

String data = "20/dsauh'03*/2021";

My idea was to do something like:

Pattern p = Pattern.compile("([0-9]{1,2}\\/[0-9]{1,2}\\/[0-9]{4})"); 
        
Matcher matcher = p.matcher(data);
        
if (matcher.find()) {
    result = matcher.group();
}

However, this regex I’m applying doesn’t ignore the characters in the middle of the String data I gave you as an example. I would like to know if you can apply a regex that captures a date in the dd/MM/yyyy format and still ignore if there are other characters in the middle?

  • 3

    It does, but it depends a lot on what you might have in the middle. If it is, for example, 20/a1b0c03d04/2021, what exactly do you want to ignore? The "a1b0" seems "obvious", but the "b03d04" is to ignore the 03 or the 04? Depending on the possibilities, it may be simple or impossible to detect all cases (and without more context, is what you can suggest...)

  • Hi, how are you? I know it is almost impossible to detect all cases, so for this case just ignore characters such as letters and other special characters other than the / bar that would be among the numbers belonging to the date. If you have another number in the middle of the date I can create a method to think about how to treat after that.

  • Maybe this will do: https://ideone.com/JfplQb

No answers

Browser other questions tagged

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