Hone

Lessons · Regex · re.escape: anything a person typed

What a person typed is not a pattern

re.escape backslashes every character that could be special, so the result matches the text and nothing else.

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 search box that compiles whatever it is handed gives wrong answers on any punctuation, and hangs on a pattern somebody chose to hang it with.

How to think about it

Anything from a person, a file or a URL goes through re.escape before it goes near a pattern. Cap the length while you are there.

Worked example

re.search('1+1', 'what is 1+1?')
1+ means one or more 1s, so the text is not found.
re.search(re.escape('1+1'), 'what is 1+1?').group()
Escaped, it means itself.
re.escape('a.b*c')
Every operator, made literal.

Your turn

Search for the text a person typed, literally.

re.search(re.('1+1'), 'what is 1+1?').group()

The trap

Wrong answers are the visible half. The other half is that a nested quantifier typed into your search box is a denial-of-service hole.

Practise re.escape: anything a person typed on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.