I want to Search for a section of a String in a data file and replace it.
No problem doing it if the Exact Text in the section of interest is known but, I seem unable to do it if the Exact Text is not fully known.
The contents of the String(s) may be different (may be Numbers or Names or, mixed).
The String(s) are read from a file, get replaced and are written back to file.
I tried many combinations of Regular Expression Syntax and get Close but never what I need…
I want to replace any/all number-pairs in the section of interest with 0.0 0.0 (no comma)
Example:
Results for the Code below are:
The Original String
(cat 5.34 8.763) kenneled in:
The Replaced String
(dog 0.0 0.0)5.34 8.763) kenneled in:
I Want Replaced String to be:
(dog 0.0 0.0) kenneled in:
data = '(cat 5.34 8.763) kenneled in:' # Section of the String
pattern = '[(cat *? )]+' # test the String
repl = '(dog 0.0 0.0)' # replace it with this
print('The Original String')
print(data + '\n')
result = re.sub(pattern, repl, data, count=1)
print('The Replaced String')
print(result)
>Solution :
IIUC, change the regular expression to (regex101 demo):
import re
s = "(cat 5.34 8.763) kenneled in:"
s = re.sub(r"[^(]+ \d+\.?\d* \d+\.?\d*", "dog 0.0 0.0", s)
print(s)
Prints:
(dog 0.0 0.0) kenneled in: