带可选前置特殊字符的YYYY-MM-DD格式日期正则表达式需求
Got it, let's break down how to build this regex to cover all your required scenarios.
First, let's outline what we need to match:
- Optional comparison operators:
>,>=,<,<=(these can appear zero or one time at the start) - A strictly formatted date in
YYYY-MM-DDstyle
Step 1: Build the date format regex
First, let's create the regex for the YYYY-MM-DD date itself. This ensures we only accept valid month (01-12) and day (01-31) values:
\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])
Let's break this down:
\d{4}: Matches exactly 4 digits for the year (e.g., 1978, 2024)(0[1-9]|1[0-2]): Matches valid months: 01-09 or 10-12(0[1-9]|[12]\d|3[01]): Matches valid days: 01-09, 10-29, or 30-31
Step 2: Add optional comparison operators
Next, we need to allow the optional prefix operators. We'll use a non-capturing group (?:...) to wrap the operators so we don't capture them unnecessarily, and add a ? to make the group optional:
(?:>|>=|<|<=)?
Step 3: Combine everything into the final regex
Putting it all together with start (^) and end ($) anchors to ensure we match the entire string (no extra characters before/after):
^(?:>|>=|<|<=)?\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$
Test cases that will match:
1978-12-20(plain date)>1978-12-20(greater than)>=1978-12-20(greater than or equal)<1978-12-20(less than)<=1978-12-20(less than or equal)
Important note:
This regex validates the format of the date, but not the actual calendar validity (e.g., it will match 2024-02-30, which isn't a real date). If you need to validate that the date is a real calendar date, it's usually better to use a date parsing library in your programming language instead of trying to handle all edge cases (like leap years, varying month lengths) with regex alone—those get extremely complex.
内容的提问来源于stack exchange,提问作者Philipp M

