str.replace() v2|v3 does not recognize regular expressions.

To perform a substitution using a regular expression, use re.sub() v2|v3.

For example:

import re

line = re.sub(
           r"(?i)^.*interfaceOpDataFile.*$", 
           "interfaceOpDataFile %s" % fileIn, 
           line
       )

In a loop, it would be better to compile the regular expression first:

import re

regex = re.compile(r"^.*interfaceOpDataFile.*$", re.IGNORECASE)
for line in some_file:
    line = regex.sub("interfaceOpDataFile %s" % fileIn, line)
    # do something with the updated line
Answer from Andrew Clark on Stack Overflow
Discussions

How to search for regex and replace with a modified version?
You can pass match object to a function in the replacement section. That function will then do the necessary transformation and return a string. I have a couple of examples here: lambda example function example More on reddit.com
🌐 r/learnpython
5
3
March 10, 2021
How do I incorporate   in regular expressions ?
You can stick it in a string with hex escape codes. 160 would be '\xa0', if I can do math this late at night. See if your regex engine works if you just stick some of those in the literal. More on reddit.com
🌐 r/Python
13
10
June 18, 2014
How do you replace a character in a string with a single backslash?

r/learnpython is probably a better subreddit for these kinds of questions.

Having said that, your first example actually works, try:

print("apple".replace('l', '\\'))
More on reddit.com
🌐 r/Python
7
0
March 16, 2015
Code for removing brackets and their contents in Python. I'm sure someone might find a use for it.

Why not just use regex?

More on reddit.com
🌐 r/Python
10
0
June 16, 2015
🌐
Python documentation
docs.python.org › 3 › howto › regex.html
Regular expression HOWTO — Python 3.14.7 documentation
If the pattern isn’t found, string is returned unchanged. The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. The default value of 0 means to replace all occurrences. Here’s a simple example of using the sub() method.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Replace Strings in Python: replace(), translate(), and Regex | note.nkmk.me
May 4, 2025 - Use the | operator to match multiple patterns. Each pattern may include special regex characters or literal substrings. This allows you to replace different substrings with the same string.
🌐
Real Python
realpython.com › replace-string-python
How to Replace a String in Python – Real Python
October 22, 2025 - In this tutorial, you'll learn how to remove or replace a string or substring. You'll go from the basic string method .replace() all the way up to a multi-layer regex pattern using the sub() function from Python's re module.
🌐
Squash
squash.io › how-to-replace-regex-in-python
How To Replace Text with Regex In Python - Squash Labs
September 24, 2023 - In this example, the regex pattern [aeiou] matches any vowel in the input string. The occurrences of the vowels are replaced with asterisks using the re.sub() function. Related Article: How to Work with Encoding & Multiple Languages in Django · Another approach to replacing regex patterns in Python is by using regex groups and backreferences.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-substituting-patterns-in-text-using-regex
Python - Substituting patterns in text using regex - GeeksforGeeks
July 12, 2025 - This example demonstrates the use of mentioned shorthand character classes for the substitution and preprocessing of text to get clean and error-free strings. Below is the implementation. ... # Python implementation of Substitution using # shorthand character class and preprocessing of text # importing regex module import re # Function to perform # operations on the strings def substitutor(): # list of strings S = ["2020 Olympic games have @# been cancelled", "Dr Vikram Sarabhai was +%--the ISRO’s first chairman", "Dr Abdul Kalam, the father of India's missile programme"] # loop to iterate e
Find elsewhere
🌐
Index.dev
index.dev › blog › regex-advanced-string-replacement-python
Python Regex Replace: How to Replace Strings Using re Module
In this example, the pattern r"(\w+), (\w+)" captures the last name and first name separately. The replacement string r"\2 \1" refers to these captured groups, swapping their order.
🌐
Linux Hint
linuxhint.com › python_string_replacement
Python String Replacement using Pattern – Linux Hint
Some uses of the above-mentioned metacharacters with sub() method are shown in the following string replacement examples. If you know the exact string value that you want to search in the main string then you can use the searching string value as a pattern in sub() method. Create a python file with the following script. Here, the searching string value is ‘rainy’ and the replacing string value is ‘sunny’. #!/usr/bin/env python3 # Import regex module import re # Define a string orgStr = "It is a rainy day" # Replace the string repStr = re.sub("rainy", "sunny", orgStr) # Print the original string print("Original Text:", orgStr) # Print the replaced string print("Replaced Text:", repStr)
🌐
Codedamn
codedamn.com › news › python
Python replace regex for searching and replacing strings
July 1, 2023 - In this example, the re.sub() function is used to replace all occurrences of 'codedamn' with 'CODEDAMN'. The output would be: Hello, CODEDAMN coders! Welcome to CODEDAMN community! The real power of regex comes with its ability to use special characters to construct search patterns, making it a vital tool for string manipulations in Python...
🌐
EDUCBA
educba.com › home › software development › software development tutorials › python string tutorial › python regex replace
Python regex replace | Learn the Parameters of Python regex replace
May 13, 2024 - In this article, we are discussing ... with some specified patterns using regular expressions, so to do this, we have to use the sub() method....
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Medium
medium.com › @wepypixel › complete-python-regex-replace-guide-using-re-sub-pypixel-9b30b2604d7a
Complete Python Regex Replace Guide using re.sub() | PyPixel | by Stilest | Medium
December 8, 2023 - In our second example, we will remove all the whitespaces that are occurring in the string. Here’s the code for same: import re text = "Remove Whitespace from this text" trimmmed_text = re.sub(r"\s", "", text) print(trimmmed_text) # Output: RemoveWhitespacefromthistext · The “\s” pattern matches all the whitespaces in the text and replace the whitespace by closing it with “”. In case you need to extract a domain from a given , you can use regex to specify this pattern: r"^https?://(www\.?"
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.Series.str.replace.html
pandas.Series.str.replace — pandas 3.0.5 documentation
When pat is a string and regex is True, the given pat is compiled as a regex. When repl is a string, it replaces matching regex patterns as with re.sub().
🌐
PYnative
pynative.com › home › python › regex › python regex replace pattern in a string using re.sub()
Python Regex Replace Pattern in a string using re.sub()
July 19, 2021 - import re # original string target_str = "Jessa knows testing and machine learning" # replace only first occurrence res_str = re.sub(r"\s", "-", target_str, count=1) # String after replacement print(res_str) # Output 'Jessa-knows testing and machine learning' # replace three occurrence res_str = re.sub(r"\s", "-", target_str, count=3) print(res_str) # Output 'Jessa-knows-testing-and machine learning'Code language: Python (python) Run · We saw how to find and replace the regex pattern with a fixed string in the earlier example.
🌐
Python documentation
docs.python.org › 3 › library › re.html
re — Regular expression operations — Python 3.14.7 ...
However, Unicode strings and 8-bit strings cannot be mixed: that is, you cannot match a Unicode string with a bytes pattern or vice-versa; similarly, when asking for a substitution, the replacement string must be of the same type as both the pattern and the search string. Regular expressions use the backslash character ('\') to indicate special forms or to allow special characters to be used without invoking their special meaning. This collides with Python’s usage of the same character for the same purpose in string literals; for example, to match a literal backslash, one might have to write '\\\\' as the pattern string, because the regular expression must be \\, and each backslash must be expressed as \\ inside a regular Python string literal.
🌐
W3Schools
w3schools.com › python › ref_string_replace.asp
Python String replace() Method
Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... The replace() method replaces a specified phrase with another specified phrase.
🌐
Plain English
python.plainenglish.io › the-incredible-power-of-pythons-replace-regex-6cc217643f37
The incredible power of Python’s replace regex | by Josh Weinstein | Python in Plain English
November 1, 2020 - In the first argument to the re.sub ... in the regex, of three, three, and four digits long, respectively. This pattern is designed to match 10 digit phone numbers which have no format that’s usually used in contact information or distinguishes the area code. The second argument, the replace string, is a template string which specifies the interpolation of the captured groups. In Python’s regex, ...
🌐
JanBask Training
janbasktraining.com › community › python-python › python-replace-regex
python .replace() regex | JanBask Training Community
May 7, 2025 - It does not interpret patterns, special characters, or regex tokens. ... Nothing changes because `d+` is treated as a literal string, not a pattern. ... Now it replaces all digit sequences dynamically. ... In practical applications like backend systems for streaming platforms or media apps (for example, handling video titles, subtitle formatting, or API responses in apps like Magis TV for PC) `re.sub()` becomes extremely useful.
🌐
PythonTest
pythontest.com › python › regex-search-replace
Python regex Search and Replace Examples | PythonTest
I also may want to make a backup of example.txt first. We can all of those things, as I’ll show below. I think the most basic form of a search/replace script in python is something like this: import fileinput import re for line in fileinput.input(): line = re.sub('foo','bar', line.rstrip()) print(line) The fileinput module takes care of the stream verses filename input handling. The re (regex, regular expression) module has sub which handles the search/replace.