Question

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

Was it helpful?

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.

OTHER TIPS

Don't forget to use a backslash before the regex symbols:

    String pattern = "\\d{2}";

Explaining the used symbols in Antoniossss answer:

  • \d Any digit, short for [0-9]
  • \s A whitespace character
  • {X} Occurs X number of times, {} describes the order of the preceding liberal

    e.g.: \d{2} searches for two digits

  • X|Z Finds X or Z.
For learning more about regular expressions in Java, I can recommend you the following tutorial: http://www.vogella.com/articles/JavaRegularExpressions/article.html

You can use a short expression which checks for a starting digit and two word characters:

"\\d+.+\\d+.\\w{2}"

I use rubular.com to check my regex.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top