Replacing multiple items with regex in Python

2019-08-04 02:39发布

问题:

I have a text file that contains certain string sequences that I want to modify. For example, in the following string I would like to replace foo and bar each with a unique string (The new string will be based on what originally matches, so I won't know it before hand).

Original: foo text text bar text
Replaced: fooNew text text bar_replaced text

I am using regex to find the groups that I need to change based on how they are delimited in the actual text. If I just use re.findAll(), I no longer have the location of the words in the string to reconstruct the string after modifying the matched groups.

Is there a way to preserve the location of the words in the string while modifying each match separately?

回答1:

Option 1

I would recommend this for complicated scenarios. Here's a solution with re.sub and a lambda callback:

In [1]: re.sub('foo|bar', lambda x: 'fooNew' if x.group() == 'foo' else 'bar_replaced', text)
Out[1]: 'fooNew text text bar_replaced text'

Option 2

Much simpler, if you have hardcoded strings, the replacement is possible with str.replace:

In [2]: text.replace('foo', 'fooNew').replace('bar', 'bar_replaced')
Out[2]: 'fooNew text text bar_replaced text'