"0000-22N-06W-01"
"0000-22N-06W-02"
"0000-22N-06W-03"
"0000-22N-06W-04"

import re
output = open("output.txt","w")
input = open("input.txt")

for line in input:
    output.write(re.sub(r'^(.{4})-(.{3})-(.{3})-(.{2})$', r'\1-\4-\2-\3', line))

input.close()
output.close()

NOTE: If you actually have " in your data then you should change your regular expression to this one:

^"(.{4})-(.{4})-(.{3})-(.{3})"$

Regex101 Demo

Answer from Ibrahim Najjar on Stack Overflow
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Replace Strings in Python: replace(), translate(), and Regex | note.nkmk.me
May 4, 2025 - re.subn() โ€” Regular expression operations โ€” Python 3.13.3 documentation
Discussions

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
linux - Python re.sub specific syntax - Stack Overflow
I am writing a script in python that replaces specific lines in files Linux. Say i have a file called hi in the /home directory that contains: hi 873840 Here is my script: #! /usr/bin/env python More on stackoverflow.com
๐ŸŒ stackoverflow.com
November 16, 2017
Use of re.sub for renaming files/strings not working
Hi, I have a scenario where I need to use an existing function of re.sub for renaming a particular file. we have a file at a particular location with a .zip extension as like abc.zip. and I have a string like bcd, I need to rename the abc name of the file using re.sub to bcd. More on discuss.python.org
๐ŸŒ discuss.python.org
19
0
October 26, 2022
python - re.sub - File path - Stack Overflow
To subscribe to this RSS feed, copy and paste this URL into your RSS reader. More on stackoverflow.com
๐ŸŒ stackoverflow.com
March 9, 2018
๐ŸŒ
Blogger
letconex.blogspot.com โ€บ 2018 โ€บ 01 โ€บ python-for-regex-search-and-replace.html
Compiled blog: Python for regex search and replace
January 25, 2018 - # import the needed modules (re is for regex) import os, re # set the working directory for a shortcut os.chdir('D:/test') # open the source file and read it fh = file('file.txt', 'r') subject = fh.read() fh.close() # create the pattern object. r means the string is send 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('file.txt', 'w') f_out.write(result) f_out.close() See also Python re.match Example for re.sub() usage in Python ยท
๐ŸŒ
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.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ re-sub-python-regex
re.sub() - Python RegEx - GeeksforGeeks
July 23, 2025 - re.sub() method in Python parts of a string that match a given regular expression pattern with a new substring.
๐ŸŒ
ProgramCreek
programcreek.com โ€บ python โ€บ example โ€บ 21 โ€บ re.sub
Python Examples of re.sub
Args: notebook : string notebook name in folder/notebook format """ notebook_path = os.path.join(*([NOTEBOOKS_DIR] + notebook.split('/'))) + ".ipynb" # Read the notebook and set epochs to num_epochs. with io.open(notebook_path, 'r', encoding='utf-8') as f: notebook = f.read() # Set number of epochs to 1. modified_notebook = re.sub(EPOCHS_REGEX, 'epochs = 1', notebook) # Replace the original notebook with the modified one. with io.open(notebook_path, 'w', encoding='utf-8') as f: f.write(modified_notebook) ... def get_header_guard_dmlc(filename): """Get Header Guard Convention for DMLC Projects.
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ library โ€บ re.html
re โ€” Regular expression operations โ€” Python 3.14.7 ...
This module provides regular expression matching operations similar to those found in Perl. Both patterns and strings to be searched can be Unicode strings (str) as well as 8-bit strings (bytes). 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.
Find elsewhere
๐ŸŒ
Squash
squash.io โ€บ replacing-strings-in-python-using-re-sub
How to Replace Strings in Python using re.sub - Squash Labs
June 8, 2023 - Substitutions ... The function takes a pattern that it looks for in the provided string. Once located, it replaces the pattern with the repl argument. The count argument defines how many occurrences of the pattern are replaced, with the default being all occurrences (0). The flags argument can modify the pattern matching, for instance making it case-insensitive. Related Article: How to Use Python's Numpy.Linalg.Norm Function
๐ŸŒ
Python Examples
pythonexamples.org โ€บ python-re-sub
Python re.sub() โ€“ Replace using Regular Expression
In this example, we will take a string and replace patterns that contains a continuous occurrence of numbers with the string NN. We will do the replacement using re.sub() function.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Use of re.sub for renaming files/strings not working - Python Help - Discussions on Python.org
October 26, 2022 - Hi, I have a scenario where I need to use an existing function of re.sub for renaming a particular file. we have a file at a particular location with a .zip extension as like abc.zip. and I have a string like bcd, I need to rename the abc name of the file using re.sub to bcd.
๐ŸŒ
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 target_str = "Jessa knows testing and machine learning" res_str = re.sub(r"\s", "_", target_str) # String after replacement print(res_str) # Output 'Jessa_knows_testing_and_machine_learning'Code language: Python (python) Run
๐ŸŒ
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 - The re.sub() method in Python provides powerful search and replace functionality using regular expressions. The regex replace works by specifying the string to modify, defining a regex pattern to match against, and providing a replacement substring.
๐ŸŒ
Liferea
lzone.de โ€บ examples โ€บ Python re.sub
LZone
LZone - Cheat Sheets for Sysadmin / DevOps / System Architecture
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ memory efficient re.sub?
r/learnpython on Reddit: Memory Efficient re.sub?
December 5, 2017 -

I have a very large file for which I need to do some regex that are multiline and re.DOTALL.

Since I do not know the size of a match a priori, I can't read the file line-by-line (or even with some windowed line as I attempted originally).

It turns out for finding regex matches, mmap should work well in theory (I actually havenโ€™t tested it on the large file yet).

So here is the real question: while I can use mmap to read me file, if I use re.sub it returns a string! No bueรฑo! Is there a way to do re.sub without loading the file into memory?

Any suggestions?

As an aside, my other thought was that I could make a limitation that be matched block be less than, say 4kb. Then I could read the file in 4k blocks and apply a search with a window of 8k. That works well for searching the file (and I actually like this more since I am not relying on mmap being efficient). But, again for replacement, it becomes increasingly difficult since I need to know if a substitution happened across the blocks to write it. Then I started to think of ways to detect if there is a gap over my blocks (edit: match between blocks of data). It got really complicated really quickly. I am not giving up on this approach, but I wanted to solicit feedback before I keep working on it

The other issue with this approach is that if I read the file by bytes and then decode it, a more-than-one-byte character can be spliced.

EDIT: I should clarify, but I probably could read the whole file into memory but I think this is also an interesting challenge!

๐ŸŒ
Javatpoint
javatpoint.com โ€บ re-sub-function-in-python
re.sub() function in python - Javatpoint
re.sub() function in python with tutorial, tkinter, button, overview, canvas, frame, environment set-up, first python program, etc.
Top answer
1 of 5
9

You could try this:

>>> import re    
>>> text = 'file1 file2 file3'
>>> x = re.sub(r'file([1-9])',r'file0\1',text)
'file01 file02 file03'

The brackets wrapped around the [1-9] captures the match, and it is the first match. You will see I used it in the replace using \1 meaning the first catch in the match.

Also, if you don't want to add the zero for files with 2 digits or more, you could add [^\d] in the regexp:

x = re.sub(r'file(1-9)',r'file0\1',text)

A bit more of a generic solution now that I'm revisiting this answer using str.format() and a lambda expression:

import re
fmt = '{:03d}'                 # Let's say we want 3 digits with leading zeroes
s = 'file1 file2 file3 text40'
result = re.sub(r"([A-Za-z_]+)([0-9]+)", \
                lambda x: x.group(1) + fmt.format(int(x.group(2))), \
                s)
print(result)
# 'file001 file002 file003 text040'

A bit of details about the lambda expression:

lambda x: x.group(1) + fmt.format(int(x.group(2)))
#         ^--------^   ^-^        ^-------------^
#          filename   format     file number ([0-9]+) converted to int
#        ([A-Za-z_]+)            so format() can work with our format

I am using the expression [A-Za-z_]+ assuming the filename contains letters and underscores only besides the training digits. Do pick a more appropriate expression if required.

2 of 5
2

To match files with single digit on the end, use a word boundary \b:

>>> text = ' '.join('file{}'.format(i) for i in range(12))
>>> text
'file0 file1 file2 file3 file4 file5 file6 file7 file8 file9 file10 file11'
>>> import re
>>> re.sub(r'file(\d)\b',r'file0\1',text)
'file00 file01 file02 file03 file04 file05 file06 file07 file08 file09 file10 file11'
๐ŸŒ
Real Python
realpython.com โ€บ lessons โ€บ replace-string-python-resub
Use re.sub() (Video) โ€“ Real Python
This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas. ... 00:00 Create a new file named transcript_re_sub.py. First, you need to import the re module. Then you can paste the transcript from before, and again youโ€™re using transcript as the variable name, with a triple-quote string that contains the chat transcript.
Published: August 22, 2023