LearnFrenzy
Sign in Take a free test

Regular Expressions · Regular Expressions Coding Problems · Question 5

Convert dates in several formats to ISO format with regex in Python Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Find dates written as DD/MM/YYYY, DD-MM-YYYY or DD.MM.YYYY in a text and rewrite them all as YYYY-MM-DD.

Solution
main.py Run
import re

text = "Exams: 05/12/2026, 18-12-2026 and 7.1.2027; results 30-01-2027."
DATE = re.compile(r"\b(\d{1,2})([/.-])(\d{1,2})\2(\d{4})\b")

def to_iso(m):
    day, month, year = int(m.group(1)), int(m.group(3)), m.group(4)
    return f"{year}-{month:02d}-{day:02d}"

print(DATE.sub(to_iso, text))

Output Verified by running it on Python 3

Exams: 2026-12-05, 2026-12-18 and 2027-01-07; results 2027-01-30.

\2 requires the second separator to equal the first, so mixed forms like 05/12-2026 are not matched. A function replacement pads day and month.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links