# The following code will search 'MM/DD/YYYY' (e.g. 11/30/2016 or NOV/30/2016, etc ),
# and replace with 'MM-DD-YYYY' in multi-line mode.
import re
with open ('input.txt', 'r' ) as f:
    content = f.read()
    content_new = re.sub('(\d{2}|[a-yA-Y]{3})\/(\d{2})\/(\d{4})', r'\1-\2-\3', content, flags = re.M)
Answer from Quinn on Stack Overflow
🌐
PythonTest
pythontest.com › python › regex-search-replace
Python regex Search and Replace Examples | PythonTest
I think the most basic form of ... care of the stream verses filename input handling. The re (regex, regular expression) module has sub which handles the search/replace....
Discussions

python - Replace all regex matches in a file - Stack Overflow
Consider a basic regex like a(.+?)a. How can one replace all occurences of that regex in a file with the content of the first group? ... Save this answer. ... Show activity on this post. Use can use the re module to use regular expressions in python and the fileinput module to simply replace text ... More on stackoverflow.com
🌐 stackoverflow.com
August 10, 2012
How to edit a text file by using regex (the "sub" function in particular)?
it is supposed to be text.read() text is file object text.read() reads conent of file More on reddit.com
🌐 r/learnpython
4
0
June 18, 2023
python - How to replace string in a file text based on regex? - Stack Overflow
So, your changes should be at the end of file. You should create a new file and replace old_one at the end of your script. There is only one way I know if you want replace several matching groups: first of all you find word using regexp and replace it like a string without regexp. More on stackoverflow.com
🌐 stackoverflow.com
string - replacing text in a file with Python - Stack Overflow
I'm new to Python. I want to be able to open a file and replace every instance of certain words with a given replacement via Python. as an example say replace every word 'zero' with '0', 'temp' wi... More on stackoverflow.com
🌐 stackoverflow.com
People also ask

How do you replace text with a regex pattern in a file?
Read or stream the file content, apply re.sub() to each chunk or the full text, then write the result to the same file or a new file.
🌐
golinuxcloud.com
golinuxcloud.com › home › programming › replace string in file using python
Replace String in File Using Python: Same File, New File, fileinput, ...
How do you replace text in the same file in Python?
Read the file with Path.read_text(), replace the text, then write back with Path.write_text(). Use a temp-file stream for very large files.
🌐
golinuxcloud.com
golinuxcloud.com › home › programming › replace string in file using python
Replace String in File Using Python: Same File, New File, fileinput, ...
How do you replace a string in a file using Python?
For small files, read the file, call str.replace(), and write the result back. For large files, stream line by line into a temporary file, then replace the original file.
🌐
golinuxcloud.com
golinuxcloud.com › home › programming › replace string in file using python
Replace String in File Using Python: Same File, New File, fileinput, ...
🌐
Finxter
blog.finxter.com › home › learn python blog › how to search and replace a line in a file in python? 5 simple ways
How to Search and Replace a Line in a File in Python? 5 Simple Ways - Be on the Right Side of Change
August 3, 2022 - #importing the regex module import ... text, subs) Therefore, to search and replace a string in Python you can either load the entire file and then replace the contents in the same file as we did in our conventional method (Method 1) or you may opt to use a more efficient ...
🌐
GoLinuxCloud
golinuxcloud.com › home › programming › replace string in file using python
Replace String in File Using Python: Same File, New File, fileinput, and Regex
June 23, 2026 - Replace text in a Python file by reading content, applying str.replace() or re.sub(), and writing the result back. For small files, Path.read_text() and Path.write_text() are enough.
🌐
Linux Hint
linuxhint.com › python_string_replacement
Python String Replacement using Pattern – Linux Hint
Create a python file with the following script to search and replace the part of the text in the place where the pattern matches. Here, a list of email addresses is assigned as text into the variable named emails. ‘@[a-z]’ is used pattern for searching. It will search any sub-string starts with small alphabets followed by ‘@’ symbol. If any sub-string matches then it will replace that sub-string by ‘@linuxhint’. #!/usr/bin/env python3 # Import regex module import re # Define a string emails = '\n[email protected] \n[email protected] \n[email protected]' # Replace the specific part of the string based on pattern replacedText = re.sub('@[a-z]*', '@linuxhint', emails) # Print the original string print("Original Text:", emails) # Print the replaced string print("\nReplaced Text:", replacedText)
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-search-and-replace-text-in-a-file-in-python
How to search and replace text in a file in Python ? - GeeksforGeeks
September 14, 2021 - Let see how we can search and replace text using the regex module. We are going to use the re.sub( ) method to replace the text. Syntax: re.sub(pattern, repl, string, count=0, flags=0) Parameters: repl : Text you want to add · string : Text ...
Find elsewhere
🌐
Kite
kite.com › python › answers › how-to-update-and-replace-text-in-a-file-in-python
Kite is saying farewell - Code Faster with Kite
November 20, 2022 - P.S. Most of our code has been open sourced on Github here. It includes our data-driven Python type inference engine, Python public-package analyzer, desktop software, editor integrations, Github crawler and analyzer, and much more.
🌐
Jerel
jerel.co › blog › 2011 › 12 › using-python-for-super-fast-regex-search-and-replace
Jerel Unruh - Using Python for super fast regex search and replace
December 21, 2011 - (re is for regex) import os, re # set the working directory for a shortcut os.chdir('/home/jerel/Desktop') # open the source file and read it fh = file('test.sql', 'r') subject = fh.read() fh.close() # create the pattern object. Note the "r". In case you're unfamiliar with Python # this is to set the string as raw so we don't have to escape our escape characters pattern = re.compile(r'\(([0-9])*,') # do the replace result = pattern.sub("('',", subject) # write the file f_out = file('test.sql', 'w') f_out.write(result) f_out.close()
🌐
YouTube
youtube.com › php video tutorials
Python 3 Tutorial - replace text with regular expression - YouTube
replace text with other text using Python Regular Expression http://phpvideotutoriale.com
Published: May 16, 2017
Views: 4K
🌐
GitHub
github.com › aureliojargas › replace
GitHub - aureliojargas/replace: Generic file search & replace tool (python) · GitHub
You have access to the full power of Python's regex flavor. $ ./replace.py --regex -f '[aeiou]' -t '◆' file.txt th◆ q◆◆ck br◆wn f◆x $ ./replace.py -r -f '[aeiou]' -t '◆' file.txt th◆ q◆◆ck br◆wn f◆x $ If necessary, you can also apply the replacements on text coming from STDIN, using - as the file name.
Starred by 34 users
Forked by 5 users
Languages: Python 93.0% | Makefile 7.0%
🌐
Note.nkmk.me
note.nkmk.me › home › python
Replace Strings in Python: replace(), translate(), and Regex | note.nkmk.me
May 4, 2025 - In Python, you can replace strings using the replace() and translate() methods, or with regular expression functions like re.sub() and re.subn(). Additionally, you can replace substrings at specific positions using slicing.
🌐
Reddit
reddit.com › r/learnpython › how to edit a text file by using regex (the "sub" function in particular)?
r/learnpython on Reddit: How to edit a text file by using regex (the "sub" function in particular)?
June 18, 2023 -
f = open('greeneggs', 'w')
f.write('i am Sam\nSam i am\nThat Sam-i-am!\nThat Sam-i-am!\ni do not like that Sam-i-am!') 
f.close()

import re
with open('greeneggs', 'r+') as text: 
redacted_text = re.sub('i', 'I', text) 
text.write(redacted_text)

I'm trying to replace the lowercase 'i' in each line with uppercase 'I'. It's supposed to be a simple task but I cannot make it work.

I intentionally use a sample of the original "green eggs" because I want to test how it works before adding the whole wall of text. Also, please advice me how to write a lot of text on a txt file by using Python.

🌐
TutorialsPoint
tutorialspoint.com › article › How-to-search-and-replace-text-in-a-file-using-Python
How to search and replace text in a file using Python?
March 5, 2025 - import re def regex_search_and_replace(file_path, search_pattern, replace_pattern): with open(file_path, 'r') as file: file_contents = file.read() updated_contents = re.sub(search_pattern, replace_pattern, file_contents) with open(file_path, 'w') as file: file.write(updated_contents) return updated_contents # Create sample file with numbers with open('example.txt', 'w') as f: f.write("This is a test file with numbers like 123, 45, and 6.") # Replace numbers with bracketed versions result = regex_search_and_replace('example.txt', r'\b(\d+)\b', r'[\1]') print("Result:", result) Result: This is a test file with numbers like [123], [45], and [6]. Sometimes we need to preserve the original case when replacing text.
🌐
JetBrains
jetbrains.com › help › pycharm › tutorial-finding-and-replacing-text-using-regular-expressions.html
Find and replace text using regular expressions | PyCharm Documentation
3 weeks ago - If you need to search and replace in more than one file, press Ctrl+Shift+R. Enter a search string in the top field and a replace string in the bottom field. Click to enable regular expressions.
🌐
w3tutorials
w3tutorials.net › blog › replace-strings-in-a-file-using-regular-expressions
How to Replace Strings in a File Using Regular Expressions in Python: Step-by-Step Examples — w3tutorials.net
String manipulation is a cornerstone of data processing, and when dealing with files, the ability to search and replace text efficiently can save hours of manual work. Python, with its robust `re` module for regular expressions (regex), offers a powerful toolkit to handle complex string replacements in files.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-substituting-patterns-in-text-using-regex
Python - Substituting patterns in text using regex - GeeksforGeeks
July 12, 2025 - # Python implementation of substituting a # specific text pattern in a string using regex # importing regex module import re # Function to perform # operations on the strings def substitutor(): # a string variable sentence1 = "It is raining outside." # replacing text 'raining' in the string # variable sentence1 with 'sunny' thus # passing first parameter as raining # second as sunny, third as the # variable name in which string is stored # and printing the modified string print(re.sub(r"raining", "sunny", sentence1)) # a string variable sentence2 = "Thank you very very much."
🌐
HCL GUVI
studytonight.com › python-howtos › search-and-replace-a-text-in-a-file-in-python
HCL GUVI | Learn to code in your native language
February 16, 2021 - Supports JavaScript, Python, Ruby, and 20+ programming languages.Explore IDE