Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex insert

Tags:

python

regex

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?

like image 513
PKlumpp Avatar asked Jul 07 '14 14:07

PKlumpp


1 Answers

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'
>>> 
like image 174
Avinash Raj Avatar answered Oct 18 '22 15:10

Avinash Raj