Hone

Lessons · Regex · replacing with a function

A replacement that decides

Give sub a function instead of a string and it is handed the match, and whatever it returns is used.

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

Anything conditional: doubling a number, looking a code up in a table, replacing some occurrences and leaving others exactly as they were.

How to think about it

Return the new text for the ones you want changed, and m.group() unchanged for the ones you do not. That is a one-pass 'except when' without encoding it in the pattern.

Worked example

re.sub(r'\d+', lambda m: str(int(m.group()) * 2), 'a1 b20')
Each number, doubled.
re.sub(r'\d+', lambda m: m.group() if len(m.group()) > 1 else 'x', 'a1 b20')
Single digits replaced, longer ones left alone.

Your turn

Double every number in the string.

re.sub(r'\d+',  m: str(int(m.group()) * 2), 'a1 b20')

The trap

The function is given the MATCH, not the matched text. m.group() is the string; m on its own is the object.

Practise replacing with a function on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.