Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substitute specific matches using regex

Tags:

python

regex

I want to execute substitutions using regex, not for all matches but only for specific ones. However, re.sub substitutes for all matches. How can I do this?

Here is an example. Say, I have a string with the following content:

FOO=foo1
BAR=bar1
FOO=foo2
BAR=bar2
BAR=bar3

What I want to do is this:

re.sub(r'^BAR', '#BAR', s, index=[1,2], flags=re.MULTILINE)

to get the below result.

FOO=foo1
BAR=bar1
FOO=foo2
#BAR=bar2
#BAR=bar3
like image 746
Shinichi TAMURA Avatar asked May 24 '26 16:05

Shinichi TAMURA


1 Answers

You could pass replacement function to re.sub that keeps track of count and checks if the given index should be substituted:

import re

s = '''FOO=foo1
BAR=bar1
FOO=foo2
BAR=bar2
BAR=bar3'''

i = 0
index = {1, 2}

def repl(x):
    global i
    if i in index:
        res = '#' + x.group(0)
    else:
        res = x.group(0)

    i += 1
    return res

print re.sub(r'^BAR', repl, s, flags=re.MULTILINE)

Output:

FOO=foo1
BAR=bar1
FOO=foo2
#BAR=bar2
#BAR=bar3
like image 60
niemmi Avatar answered May 27 '26 04:05

niemmi