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

如何精准匹配mm/yyyy格式日期,排除mm/dd/yyyy格式干扰

Solution for Matching Standalone mm/yyyy Dates (Excluding mm/dd/yyyy Substrings)

Let's fix this regex issue once and for all. The problem with your current approach is that [^/]\d{1,2}/\d{4} doesn't properly exclude the dd/yyyy substring from mm/dd/yyyy dates—it can still grab parts of those longer dates when there's a digit before the target pattern.

The solution here is to use a negative lookbehind assertion to ensure that the mm/yyyy pattern isn't preceded by a digit followed by a slash (which would mean it's part of a mm/dd/yyyy date). Here's the regex you need:

import re
text1 = 'Appointment is on 10/06/2009. Next appointment in 07/2009'
matches = re.findall(r'(?<!\d/)\d{1,2}/\d{4}', text1)
print(matches)  # Output: ['07/2009']

How This Regex Works

  • (?<!\d/): This negative lookbehind checks that the pattern immediately before \d{1,2}/\d{4} is not a digit plus a slash. This blocks us from matching the dd/yyyy segment of a full mm/dd/yyyy date.
  • \d{1,2}/\d{4}: Your core pattern for mm/yyyy (1-2 digits for the month, 4 digits for the year).

Edge Cases Covered

  • Line-start dates: Works flawlessly—since there's nothing before the date, the negative lookbehind doesn't trigger a failure. For example, 03/2021 Lorem ipsum will correctly match 03/2021.
  • Dates with special character/letter prefixes: Captures dates like ~09/2009, X12/2018, or 05/2020 (space-prefixed) without missing them.
  • Line-end dates: No issues here—unless you need to exclude dates followed by a slash (e.g., malformed 07/2009/15), in which case add a negative lookahead: (?<!\d/)\d{1,2}/\d{4}(?!/).

Additional Test Example

Let's verify with a mix of date formats:

text2 = '~09/2009 04/2020 11/05/2019 06/2018'
matches = re.findall(r'(?<!\d/)\d{1,2}/\d{4}', text2)
print(matches)  # Output: ['09/2009', '04/2020', '06/2018']

This skips the 05/2019 substring from 11/05/2019 and correctly captures all standalone mm/yyyy dates.

内容的提问来源于stack exchange,提问作者Krishna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:44:37