Hone

Lessons · Regex · \d is more digits than you think

More digits than you think

\d means any Unicode decimal digit, which includes scripts other than this one. [0-9] means exactly those ten characters.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

If the value is going to int(), \d is fine, because Python parses those too. If it is going into a fixed-width field or a bank format, it is not.

How to think about it

Ask what the field is FOR. 'A digit' is \d. 'One of these ten characters' is [0-9], and it cannot widen underneath you later.

Worked example

re.match(r'\d+', '\u0661\u0662\u0663').group()
Arabic-Indic digits are digits.
re.match(r'[0-9]+', '\u0661\u0662\u0663')
The explicit range is not fooled.
int('\u0661\u0662\u0663')
And Python really does parse them, which is why \d is not simply wrong.

Your turn

Match only the characters 0 to 9.

+

The trap

The two agree on every English digit, so a test suite written in English never tells them apart.

Practise \d is more digits than you think on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.