如何使用Regex从HTML中提取带序数词的特定活动日期
How to Extract the Date for "Sally Molloy: Backyard Worlds" with Regex
Hey there, I’ve got a regex solution tailored to your needs—using lookarounds to zero in on the exact date tied to that event. Here’s how it works:
The Regex Pattern
This uses positive lookbehind to anchor to the event name, then captures the date/time structure you’re after:
(?<=Sally Molloy: Backyard Worlds.*?)[\d]{1,2}(?:st|nd|rd|th)\s+[A-Za-z]+,\s+\d{1,2}:\d{2}\s+-\s+\d{1,2}:\d{2}[ap]m
Let’s Break It Down
(?<=Sally Molloy: Backyard Worlds.*?): This lookbehind ensures we’re only looking for dates that come right after the event name. The.*?is non-greedy, so it won’t jump past the first matching date.[\d]{1,2}(?:st|nd|rd|th): Catches the day with its ordinal suffix (like 24th) without capturing the suffix separately.\s+[A-Za-z]+: Matches the month name (May, June, etc.).,\s+\d{1,2}:\d{2}\s+-\s+\d{1,2}:\d{2}[ap]m: Grabs the time range, including the comma, whitespace, and am/pm.
Example in Python
If you’re using Python to parse the HTML, here’s how you’d implement it:
import re # Replace this with your actual HTML snippet html = """Put your HTML content here that includes the event and date""" date_pattern = r'(?<=Sally Molloy: Backyard Worlds.*?)[\d]{1,2}(?:st|nd|rd|th)\s+[A-Za-z]+,\s+\d{1,2}:\d{2}\s+-\s+\d{1,2}:\d{2}[ap]m' match_result = re.search(date_pattern, html, re.DOTALL) if match_result: print(f"Found date: {match_result.group()}") else: print("Couldn't find the date for that event.")
The re.DOTALL flag lets the regex match across lines, which is crucial since HTML often has line breaks between elements.
Quick Tips
- If there are HTML tags between the event name and date, the non-greedy
.*?should still work, but if you run into issues, you can adjust it to something like(?<=Sally Molloy: Backyard Worlds[\s\S]*?)to explicitly match any character including newlines. - Test the regex with your actual HTML snippet to make sure it fits—small variations in the HTML structure might require tiny tweaks.
内容的提问来源于stack exchange,提问作者ManuelVillamil
相关产品推荐
相关产品推荐

