hl95 hl95 - 3 months ago 22
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

w
or
e
followed by 2 digits, such as
e77
w10
etc.

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

([e|w])\d{0,2}(\.\d{1,2})?


How can I add a space right after the letter
e
or
w
? 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.

Input:
hello e77 world


Desired output:
hello e 77 world


Thank You.

Answer

Your regex needs to just look like this:

([ew])(\d{2})

if you want to only match specifically 2 digits, or

([ew])(\d{1,2})

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'