cppcoder cppcoder -4 years ago 143
Python Question

Search & replace a substring

I want to search for a substring in a string and replace with another pattern.
The search string is in between curly braces.

Example string

line = $lang['MY_KEY'] = '{search-string} wird in Analyse berĆ¼cksichtigt';


I tried this code:

re.sub('([a-zA-Z0-9\[\]\$\' ].*{).*(}[a-zA-Z\.,; ].*)','\1replace-string\2',line)


And also:

re.sub('(.*{).*(}.*)', '\1replace-string\2', line)


I am getting some junk characters along with the replace-string in the output.

EDIT

I have one more question.

There are multiple search strings in curly braces. I want to replace each substring with different patterns. How can I do it?

Answer Source

As you have backslashes prefix the patterns and replacements with an r :-

print re.sub(r'([a-zA-Z0-9\[\]\$\' ].*{).*(}[a-zA-Z\.,; ].*)',r'\1replace-string\2',line)

print re.sub(r'(.*{).*(}.*)', r'\1replace-string\2', line)

EDIT: replace every second occurrence using a replacement function

import re
def repl(matchobj):
    global counter
    counter = counter+1
    if counter == 2: 
        return '{replace-string}' 
    else: 
        return matchobj.group(0)

counter = 0
line = "$lang['MY_KEY'] = '{search-string} wird in Analyse {search-string} bercksichtigt'";
print re.sub(r'{.*?}',repl,line)

EDIT: Use a dictionary to store the replacements

import re
def repl(matchobj):
    global counter
    replacementFor = {'{search-string1}': '{replace-string1}',
                      '{search-string2}': '{replace-string2}',
                      '{search-string3}': '{replace-string3}'}

    counter = counter+1
    if counter == 2: 
        return replacementFor.get(matchobj.group(0), matchobj.group(0))
    else: 
        return matchobj.group(0)

counter = 0
line = "$lang['MY_KEY'] = '{search-string} wird in Analyse {search-string1} bercksichtigt'";
print re.sub(r'{.*?}',repl,line)

counter = 0
line = "$lang['MY_KEY'] = '{search-string} wird in Analyse {search-string3} bercksichtigt'";
print re.sub(r'{.*?}',repl,line)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download