使用Python正则表达式提取文本中不同格式日期的问题
Hey there! Let's work through your date extraction problem—since you're getting empty results with regex and wrong outputs with datefinder, let's break down the fixes step by step.
First: Diagnose the Regex Problem
If your regex is returning empty results for multiple date formats, it's likely that your pattern isn't covering the specific formats present in your string. Let's assume your target date is 2016-08-10 (and maybe another common format like 08/10/2016 or 10-Aug-2016). Here's a robust regex pattern that covers several common formats and ensures you capture the correct date:
import re from datetime import datetime # Regex pattern covering YYYY-MM-DD, MM/DD/YYYY, DD-Mon-YYYY formats date_pattern = r'\b(?:\d{4}-\d{2}-\d{2}|\d{2}/\d{2}/\d{4}|\d{2}-\w{3}-\d{4})\b' your_string = "Your input string containing dates here" matches = re.findall(date_pattern, your_string) # Convert matches to consistent datetime format for match in matches: try: date_obj = datetime.strptime(match, '%Y-%m-%d') except ValueError: try: date_obj = datetime.strptime(match, '%m/%d/%Y') except ValueError: date_obj = datetime.strptime(match, '%d-%b-%Y') # Output in your desired format: YYYY-MM-DD 00:00:00 print(date_obj.strftime('%Y-%m-%d %H:%M:%S'))
If your dates have extra variations (like optional time components or non-standard separators), adjust the regex pattern—for example, add (?:\s\d{2}:\d{2}:\d{2})? to capture optional time strings.
Fixing datefinder's Incorrect Output
datefinder can sometimes pick up false positives or misparse dates if there are interfering numeric strings in your input. To force it to prioritize the correct 2016-08-10 result, try these tweaks:
import datefinder from datetime import datetime your_string = "Your input string here" matches = list(datefinder.find_dates(your_string)) # Define your target date to validate matches against target_date = datetime(2016, 8, 10) correct_match = None for match in matches: # Check if the date part matches (ignore time if needed) if match.date() == target_date.date(): # Normalize time to 00:00:00 correct_match = match.replace(hour=0, minute=0, second=0) break if correct_match: print(correct_match.strftime('%Y-%m-%d %H:%M:%S')) else: # Fall back to regex if datefinder fails print("Falling back to regex extraction...") # Insert the regex code block from above here
Another quick fix: if your target date is always in a specific section of the string, slice the string first before passing it to datefinder to reduce noise from other numbers.
Common Pitfalls to Watch For
- Hidden characters: Sometimes strings have invisible whitespace or non-ASCII separators (like en dashes instead of hyphens). Use
your_string = re.sub(r'[^\w\s/]', '-', your_string)to normalize these characters. - Ambiguous formats: Dates like
08/10/2016can be parsed as MM/DD/YYYY or DD/MM/YYYY—explicitly validate matches against your expected date to avoid this confusion.
内容的提问来源于stack exchange,提问作者user9431057

