PKlumpp
PKlumpp

Reputation: 5233

Python regex insert

I have a String s

s = "x01777"

Now I want to insert a - into s at this position:

s = "x01-777"

I tried to do this with re.sub() but I can't figure out how to insert the - without deleting my regex (I need this complex structure of regex because the String I want to work with is much longer).

Actually, it looks something like this:

re.sub('\w\d\d\d\d\d', 'here comes my replacement', s)

How do I have to set up my insertion?

Upvotes: 15

Views: 25405

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174696

Capture the first three characters into a group and then the next three to another group. In the replacement part just add - after the first captured group followed by the second captured group.

>>> import re
>>> s = "x01777"
>>> m = re.sub(r'(\w\d\d)(\d\d\d)', r'\1-\2', s)
>>> m
'x01-777'
>>> 

Upvotes: 28

Related Questions