Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex: how to replace each instance of an occurrence with a different value?

Tags:

python

regex

Suppose I have this string: s = "blah blah blah"

Using Python regex, how can I replace each instance of "blah" with a different value (e.g. I have a list of values v = ("1", "2", "3")

like image 284
zer0stimulus Avatar asked Sep 03 '11 14:09

zer0stimulus


People also ask

How can I do multiple substitutions using regex?

So in your case, you could make a dict trans = {"a": "aa", "b": "bb"} and then pass it into multiple_replace along with the text you want translated. Basically all that function is doing is creating one huge regex containing all of your regexes to translate, then when one is found, passing a lambda function to regex.

How do you replace all occurrences of a regex pattern in a string Python?

sub() method will replace all pattern occurrences in the target string. By setting the count=1 inside a re. sub() we can replace only the first occurrence of a pattern in the target string with another string. Set the count value to the number of replacements you want to perform.

How do you replace all occurrences of a string in Python?

The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.

WHAT IS RE sub () in Python?

sub() function belongs to the Regular Expressions ( re ) module in Python. It returns a string where all matching occurrences of the specified pattern are replaced by the replace string. To use this function, we need to import the re module first. import re.


4 Answers

You could use a re.sub callback:

import re
def callback(match):
    return next(callback.v)
callback.v=iter(('1','2','3'))

s = "blah blah blah"
print(re.sub(r'blah',callback,s))

yields

1 2 3
like image 152
unutbu Avatar answered Oct 27 '22 02:10

unutbu


You could use re.sub, which takes a string or function and applies it to each match:

>>> re.sub('blah', lambda m, i=iter('123'): next(i), 'blah blah blah')
<<< '1 2 3'
like image 37
zeekay Avatar answered Oct 27 '22 01:10

zeekay


In this case, you don't need regex:

s.replace("blah","%s")%v

the replace produces "%s %s %s", then you use the format operator

like image 31
Foo Bah Avatar answered Oct 27 '22 02:10

Foo Bah


I think you don't really need a regex.

for x in v:
  s = s.replace('blah', x, 1)

However if you really wanted a regex:

import re
for x in v:
  s = re.sub('blah', x, s, count=1)
like image 45
wim Avatar answered Oct 27 '22 02:10

wim