Reputation: 455
I have test file(test.txt) as below:
`RANGE(vddout,sup)
`RANGE(vddin,sup_p)
I would like to modify this file as below:
`RANGE(vddout,sup,tol_sup)
`RANGE(vddin,sup_p,tol_sup_p)
Here is the code I tried but its not able to find and the replace the pattern using re.search. Could you point out where is the flaw in the code?
with open("test.txt", 'r+') as file :
for line in file:
print("line={}".format(line))
findPattern=re.search(r'(`RANGE\(\w+,(\w+))\)',line)
if findPattern:
print("findPattern={}".format(findPattern))
line=re.sub(r'(`RANGE\(\w+,(\w+))\)',r'\1,tol_\2',line)
Upvotes: 5
Views: 172
Reputation: 3801
As mentioned in the comments, you aren't writing the file.
Moreover, you are reading each line one by one when you could just be reading the entire file as a string to perform your manipulation. This is both inefficient (as you need to perform re.sub
multiple times) and more complicated* to code (as you need to create a new string to write to the file).
Finally, you are performing re.match
and re.sub
. This is unnecessary as re.sub
will simply do nothing if there is no match; you don't need to check first.
In [188]: with open('test.txt', 'r+') as f:
...: data = f.read()
...: updated = re.sub(r'(`RANGE\(\w+,(\w+))', r'\1,tol_\2', data)
...: f.seek(0) # Start writing at the beginning of the file
...: f.write(updated)
*Note: more complex but not difficult
Upvotes: 2
Reputation: 1362
This should work. (you don't have to search first and then replace. You can directly attempt to replace. It only replaces if it matches in the first place)
import re
with open("test.txt", 'r+') as file :
for line in file:
print(line)
print(re.sub(r'`RANGE\((\w+),(\w+)\)', r'`RANGE(\1,\2,tol_\2)`', line))
Upvotes: 2