ZhangZhihui's Blog  

Why does string '10/12/2007' match Python regular expression '\d{2}/\d{2}/\d{4}' but not match '\d{1, 2}/\d{1, 2}/\d{4}'?

 

You might expect it to match one or two digits (which seems reasonable for a date like 10/12/2007), but it doesn't—because of the space in {1, 2}.

In Python regex syntax, you must not include a space between the numbers inside the quantifier.

❗Incorrect:

\d{1, 2}  # NOT valid syntax

This is not a valid quantifier and will cause the regex to be parsed incorrectly.

✅ Correct:

\d{1,2}

No space between 1 and 2.

 

How to write the regular expression quantifier if I only want to match 2 or 4 digits?

If you want to match either 2 digits OR 4 digits, the standard quantifier alone (like {2,4}) won’t work as you expect—it matches any number of digits between 2 and 4.

Instead, you’ll want to use the alternation operator (|) like this:

(?:\d{2}|\d{4})

Explanation:

  • \d{2}: matches exactly 2 digits

  • \d{4}: matches exactly 4 digits

  • |: means “or”

  • (?:...): a non-capturing group, used to group the alternation without creating a capture group

 

A Python Regular Expression Editor: https://pythex.org

posted on 2025-04-15 21:31  ZhangZhihuiAAA  阅读(7)  评论(0)    收藏  举报