1

I having problems to generate a regex for a range of dates. For example this range [2015-11-17, 2017-10-05], How can I do? to validate if having a date belogns to that range using regex.

And second question if is possible to have a generic regex which I can use for several range of date, only replacing few values in the regex with the new ranges I have, and the regex continues validating a range of dates , but with the new ranges. Thanks in advance for help =)

3
  • 2
    Don't use regex for that, create a date object from the string and check ranges using the API. Commented Mar 8, 2016 at 13:19
  • 1
    Regex is used to validate the syntax of data, not its value. Split by comma, parse LocalDate, use isBetween(start,end). Commented Mar 8, 2016 at 13:26
  • Validating range of dates with regex is a very bad idea. Simple year validation could end up like this regex. Commented Mar 8, 2016 at 13:31

2 Answers 2

1

Do not use Regex

As the comments state, Regex is not appropriate for a range of dates, nor any span of time. Regex is intended to be “dumb” in the sense of looking only at the syntax of the text not the semantics (the meaning).

java.time

Use the java.time framework built into Java 8 and later.

Parse your strings into LocalDate objects.

LocalDate start = LocalDate.parse( "2015-11-17" );

Compare by calling the isEqual, isBefore, and isAfter methods.

Note that we commonly use the Half-Open approach in date-time work where the beginning is inclusive while the ending is exclusive.

These issues are covered already in many other Questions and Answers on Stack Overflow. So I have abbreviated my discussion here.

Sign up to request clarification or add additional context in comments.

Comments

0

Just for completeness: You can actually use regular expressions to recognize any finite set of strings, such as a specific date range, however it would be more of an academic exercise than an actual recommended usage. However, if you happen to be programming some arcane hardware it could actually be necessary.

Assuming the input is always a valid date in the given format, the regex for your example could consist of:

2015-0[1-9].* - 2015 January to September

2015-10.* - 2015 October

2015-11-0[1-9] - 2015 November 1 to 9

2015-11-1[0-7] - 2015 November 10 to 17

2016.* - all dates of 2016

Add analogously for 2017, make a disjunction using | (a|b|c|...), apply escaping of the regex implementation you use and then you have your date checker. If the input is not guaranteed to be a valid date it gets a bit more complicated but is still possible.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.