Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing 'match' object with string, Python

I want to replace certain lines in my text with another string. So far I was able to locate the text I want to replace with:

text = open('sample','r').read()
regex = re.compile('.*#= min, max\s')
for match in regex.finditer(text):
    print match.group(0) #this is what i want to replace

EDIT: also tried

text = open('sample','r').read().split('\n')
for line in text:
    line = re.sub('.*#= min, max\s', "HOLA", line)

The text stays the same. Could it be that my regex is messed up? I used the same one somewhere else and there was no problem. Also its a simple regex.

How do I switch it to another line? Thanks!

like image 504
Yotam Avatar asked Apr 30 '26 16:04

Yotam


1 Answers

try:

subbedlines = []

with open('sample','r') as textreader:
    lines = textreader.read().split('\n')

for line in lines:
    subbedlines.append(re.sub('.*#= min, max\s', "HOLA", line))

should work if your regex is correct and your lines in the text file are matching. to write the file again simply do:

with open('sample','w') as textwriter:
    for line in subbedlines:
        textwriter.write("%s\n" % line)
like image 90
Inbar Rose Avatar answered May 03 '26 07:05

Inbar Rose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!