如何精准匹配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 thedd/yyyysegment of a fullmm/dd/yyyydate.\d{1,2}/\d{4}: Your core pattern formm/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 ipsumwill correctly match03/2021. - Dates with special character/letter prefixes: Captures dates like
~09/2009,X12/2018, or05/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
相关产品推荐
相关产品推荐

