Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace all occurrences of a substring using regex?

Tags:

I have a string, s = 'sdfjoiweng%@$foo$fsoifjoi', and I would like to replace 'foo' with 'bar'.

I tried re.sub(r'\bfoo\b', 'bar', s) and re.sub(r'[foo]', 'bar', s), but it doesn't do anything. What am I doing wrong?

like image 367
ThanksInAdvance Avatar asked Oct 12 '16 16:10

ThanksInAdvance


2 Answers

You can replace it directly:

>>> import re >>> s = 'sdfjoiweng%@$foo$fsoifjoi' >>> print(re.sub('foo','bar',s)) sdfjoiweng%@$bar$fsoifjoi 

It will also work for more occurrences of foo like below:

>>> s = 'sdfjoiweng%@$foo$fsoifoojoi' >>> print(re.sub('foo','bar',s)) sdfjoiweng%@$bar$fsoibarjoi 

If you want to replace only the 1st occurrence of foo and not all the foo occurrences in the string then alecxe's answer does exactly that.

like image 89
coder Avatar answered Sep 25 '22 00:09

coder


re.sub(r'\bfoo\b', 'bar', s)

Here, the \b defines the word boundaries - positions between a word character (\w) and a non-word character - exactly what you have matching for foo inside the sdfjoiweng%@$foo$fsoifjoi string. Works for me:

In [1]: import re  In [2]:  s = 'sdfjoiweng%@$foo$fsoifjoi'  In [3]: re.sub(r'\bfoo\b', 'bar', s) Out[3]: 'sdfjoiweng%@$bar$fsoifjoi' 
like image 40
alecxe Avatar answered Sep 26 '22 00:09

alecxe