Not working for me

I am trying to get re.sub to replace the template specified by the value, e.g.

 for lines in f: pattern='\${2}'+key[0]+'\${2}' re.search(pattern,lines) 

this returns the string in which the pattern was found. For example, this is one of the test results if it received

this is $$ test $$

The problem I am facing is when I do the following

 re.sub(pattern,key[1],lines) 

Nothing happens. What am I missing? For more information, key[0]=test and key[1]=replace so what I try to do when "$$ test $$" is encountered, it replaces it with "replacement". I have no problem finding "$$ test $$", but for some reason re.sub does not replace it.

+8
python regex
source share
2 answers

You assign the re.sub result back to a variable, right? eg.

 lines = re.sub(pattern, key[1], lines) 

This is a string, so it cannot be changed (strings are immutable in Python), so a new line is created and returned. If you do not name him, you will lose him.

+11
source share

If you have text, you can run re.sub () directly on the entire text as follows:

 import re ss = '''that a line another line a line to $$test$$ 123456 here $$test$$ again closing line''' print(ss,'\n') key = {0:'test', 1:'replace'} regx = re.compile('\$\${[0]}\$\$'.format(key)) print( regx.sub(key[1],ss) ) 

.

If you are reading a file, you should be interested in reading the entire file and placing it in the ss object before running re.sub () on it instead of reading and replacing the line after line

.

And if you have a list of strings, you should handle the following:

 import re key = {0:'test', 1:'replace'} regx = re.compile('\$\${[0]}\$\$'.format(key)) lines = ["that a line", 'another line', 'a line to $$test$$', '123456', 'here $$test$$ again', 'closing line'] for i,line in enumerate(lines): lines[i] = regx.sub(key[1],line) 

Otherwise, the line containing "$$ test $$" will not be changed:

 import re key = {0:'test', 1:'replace'} regx = re.compile('\$\${[0]}\$\$'.format(key)) lines = ["that a line", 'another line', 'a line to $$test$$', '123456', 'here $$test$$ again', 'closing line'] for line in lines: line = regx.sub(key[1],line) print (lines) 

result

 ["that a line", 'another line', 'a line to $$test$$', '123456', 'here $$test$$ again', 'closing line'] 
+2
source share

All Articles