How Can I Replace All Occurrences of a Substring Using Regex?

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?

3

4 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.

3

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'
1

You can use replace function directly instead of using regex.

>>> s = 'sdfjoiweng%@$foo$fsoifjoifoo'
>>>
>>> s.replace("foo","bar")
'sdfjoiweng%@$bar$fsoifjoibar'
>>>
>>>

To further add to the above, the code below shows you how to replace multiple words at once! I've used this to replace 165,000 words in 1 step!!

Note \b means no sub string matching..must be a whole word..if you remove it then it will make sub-string match.

import re
s = 'thisis a test'
re.sub('\bthis\b|test','',s)

This gives:

'thisis a '
8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest