hl95 hl95 - 1 year ago 107
Python Question

Insert space between characters regex

I'm very new to regex, and i'm trying to find instances in a string where there exists a word consisting of either the letter

followed by 2 digits, such as

Here's the regex that I currently have, which I think finds that (correct me if i'm wrong)


How can I add a space right after the letter
? If there are no instances where the criteria is met, I would like to keep the string as is. Do I need to use re.sub? I've read a bit about that.

hello e77 world

Desired output:
hello e 77 world

Thank You.

Answer Source

Your regex needs to just look like this:


if you want to only match specifically 2 digits, or


if you also want to match single digits like e4

The brackets are called capturing groups and could be back referenced in a search and replace, or with python, using re.sub

your replace string should look like

\1 \2

So it should be as simple as a line like:

re.sub(r'([ew])(\d{1,2})', r'\1 \2', your_string)

EDIT: working code

>>> import re
>>> your_string = 'hello e77 world'
>>> re.sub(r'([ew])(\d{1,2})', r'\1 \2', your_string)
'hello e 77 world'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download