Hone

Lessons · Regex · ASCII: back to a-z and 0-9

Narrowing it back to ASCII

re.A makes \w, \d, \s and \b mean their ASCII-only versions, across the whole pattern.

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

A hostname, a hex id, a protocol field really is ASCII. Saying so makes the pattern stricter and its intent obvious.

How to think about it

Machine format, or something a person wrote? Narrow the first; never narrow the second.

Worked example

bool(re.match(r'\d+', '\u0661\u0662\u0663'))
Unicode digits, by default.
bool(re.match(r'\d+', '\u0661\u0662\u0663', re.A))
With ASCII on, \d is [0-9] again.
re.findall(r'\w+', 'caf\xe9', re.A)
And \w narrows with it.

Your turn

Refuse digits from other scripts.

bool(re.match(r'\d+', '\u0661\u0662\u0663', re.))

The trap

Turning it on for a field that holds a person's name is the same bug as writing [a-z], with a flag instead of a range.

Practise ASCII: back to a-z and 0-9 on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.