You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

带可选前置特殊字符的YYYY-MM-DD格式日期正则表达式需求

匹配带比较运算符的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-DD style

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:51:21