Skip to content

Java RegEx – Extract Date from String

Java RegEx – Extract Date from String example shows how to extract a date from the string content using java regular expression pattern.

How to extract a date from a string using regex in Java?

Extracting the date from the string using a regex pattern is very easy. The first thing we need to do is to determine the date format. For the purpose of this example, I am assuming the date is in the format of dd-mm-yyyy. So we need to create a pattern that matches two digits for the day, followed by a “-” separator, followed by 2 digits for the month, followed by a “-” separator, and then 4 digits for the year.

Here is the regex pattern to extract the date in this format.

Where,

Let’s test this pattern.

Output

As you can see from the output, the pattern worked as expected. But wait, what about the dates “1/01/1999”, or “01/1/1999”. These dates will not match our pattern, because it expects the day and month in 2 digits. Let’s modify our pattern a little bit to include these dates as well.

Now instead of looking for 2 digits for the day and month parts, it looks for a minimum 1 digit and a maximum of 2 digits. Now this pattern will work even if the day and month are in single digits.

You can modify the above pattern to include other formats like dd/mm/yyyy, mm-dd-yyyy, mm/dd/yyyy, dd-mm-yy, dd/mm/yy, mm-dd-yy, or mm/dd/yy formats.

Any of the above patterns do not include the month in words. What about the format like “01-January-2010”? Let’s write a pattern for that as well.

The day and year parts in this pattern are the same as the previous pattern. However, we replaced the numerical month part with the month names separated by a regex OR condition using the pipe.

Output

You can also do the same for the date pattern that has short month names like Jan, Feb, etc. Please note that all of the above patterns do not validate the dates. If the string contains an invalid date like 45-55-5000, it will still extract that. Please visit Java regex validate date example to learn more about that.

If you want to learn more about the regex patterns, visit Java Regex Tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.