Master Python Regex: Extract Dates with One Powerful Pattern
This tutorial walks through building and refining a Python regular expression that reliably matches a wide range of Chinese date formats—such as "2018年6月7日", "2018/6/7", "2018-06-07" and "2018-06"—by explaining each component, testing against sample strings, and presenting the final concise pattern.
Python Regex for Date Extraction
In this article we demonstrate how to construct a regular expression in Python that can match various date formats commonly used when writing exam dates, including 2018年6月7日, 2018/6/7, 2018-06-07, 2018-06 and plain year‑month strings.
We start with a very simple pattern and iteratively improve it while testing against several example strings.
Step 1 – Match any preceding text
The token .* matches any character sequence any number of times, allowing us to ignore the surrounding text such as "高考时间是".
Step 2 – Capture the year
\d{4}matches exactly four digits, representing the year (e.g., 2018). It is followed by a character class [年/-] that accepts the Chinese character 年, a slash / or a hyphen -.
Step 3 – Capture the month
\d{1,2}matches one or two digits for the month (e.g., 6 or 06). It is followed by [月/-] to accept 月, / or -.
Step 4 – Capture the optional day
The day part is similar: \d{1,2} for one or two digits, followed by 日 or the end of the string. Because some strings omit the day, we use an alternation with the end‑anchor $ to make the day optional.
Step 5 – Combine into a full pattern
Putting the pieces together, a robust pattern looks like:
pattern = r".*高考时间是.*?(\d{4})[年/-](\d{1,2})[月/-](\d{1,2})?日?"This pattern successfully matches all six test strings shown below.
Testing results (illustrated in the images):
After the final adjustment, the pattern correctly matches all six different date representations, demonstrating the flexibility and power of regular expressions in Python.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
