Regex: match a pattern, change a part of it

regex

If you have a text file and want to search and replace a part of a matched pattern, how would you do it with perl one-liners, sed or python?

For example:

"653433,78"

match with [0-9]{6},[0-9]{2}.

Change , to ..

Best Answer

You can use numbered sub groups. i.e:

Find:

([0-9]{6}),([0-9]{2})

Replace:

\1.\2

Example in Python:

import re
inp = '653433,78'
out = re.sub(r'([0-9]{6}),([0-9]{2})', r'\1.\2', inp)
print out

This would give you:

>>>'653433.78'
Related Question