0

I would like to create a small Python regex in order to replace similar strings into several text files.

Problem is that those files may be a bit different in terms of whitespaces. For example first text file looks like this :

myString=${string_1}/${string_2}

But second text file contains the following string :

myString  = ${string_1}/${string_2}

How can I write a regex that takes both string in both files and then replace myString with myString=${string_1}_${string_2}/string3 no matter how many whitespaces there are (let's assume we do not know the exact number).

So far, my regex looks like this :

temp_dir = tempfile.gettempdir()
temp_path = os.path.join(temp_dir, 'temp_file_name')

fin = open(path, 'r')
fout = open(temp_path, 'w')
#Beginning of the regex
for line in fin:
    string = re.sub("myString=${string_1}/${string_2}", "myString=${string_1}_${string_2}/string3", line)
    fout.write(string)

fin.close()
fout.close()

return temp_path

As you can see, I do not know how to match the possibility with whitespaces within the re.sub() method.

Do you have any ideas ? Thanks.

hacks4life
  • 691
  • 5
  • 16
  • 38

0 Answers0