Search code examples
javaregexdatereplaceall

Java Regex Date Replace From Text


I have googled to find my answer but can't able to get one. Since I am very novice in Regular Expressions. I need to put my question here.

I have a text file in which I need to replace the contents having date value in "MM/dd/yyyy hh:mm:ss a" format.

Sample Contents:

<td> Order is Placed on:</td>
<td>The date and time is 12/08/2013 05:46:56 PM</td>

I need resulted output by replacing only the date value. Something like:

<td> Order is Placed on:</td>
<td>The date and time is </td>

This date value can be appeared at any place. There is no specific suffix or prefix occurring around it.

What can be the regex for above expected result in below code:

String textLine = readline.replaceAll("some_regex","");

Thank you.


The solution is :

String textLine = readline.replaceAll("\\d{2}/\\d{2}/\\d{4}\\s\\d{2}:\\d{2}:\\d{2}\\s(?:AM|PM)", "");

Thank you - @Antoniossss


Solution

  • REGEX:

    \d{2}/\d{2}/\d{4}\s\d{2}:\d{2}:\d{2}\s(?:AM|PM)
    

    This matches the general pattern, but will accept non-valid dates, which doesn't seem to be a concern for you.