Hone

Lessons · Regex · \d: any digit

Matching a digit

\d matches one digit, 0 to 9. \D matches one character that is not a digit. Uppercase is the opposite of lowercase for every such class.

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

Phone numbers, order ids, postcodes, prices: nearly every extraction starts with 'find the digits', and \d is shorter and clearer than [0-9].

How to think about it

One \d is one digit. Add a quantifier for a run: \d+ for one or more, \d{4} for exactly four. Reach for \D when you want the separators between the numbers.

Worked example

pattern: \d
One digit.
text: room 7
Matches the 7.
pattern: \d+
A run of digits.
text: order 20481 shipped
Matches 20481 in one go.
pattern: \D+
A run of non-digits.
text: 12-34
Matches the dash between the numbers.

Your turn

Exactly four digits, a year.

\d

The trap

\d can match digits from other scripts in Python's default Unicode mode. Use [0-9] when only ASCII digits are acceptable.

Practise \d: any digit on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.