Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert space between characters regex

Tags:

python

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.

like image 837
hl95 Avatar asked Dec 11 '22 15:12

hl95


2 Answers

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'
like image 91
R Nar Avatar answered Dec 25 '22 16:12

R Nar


This is what you're after:

import re

print(re.sub(r'([ew])(\d{1,2})', r'\g<1> \g<2>', 'hello e77 world'))
like image 32
Wayne Werner Avatar answered Dec 25 '22 17:12

Wayne Werner