Python: global replacement with regex
October 01, 2007 03:26:46 Last update: August 25, 2011 08:57:40
Use the
sub function in the re module to do global replacement:
import re re.sub(pattern, replacement, input) # returns the new value of the string after replacement # for example, replace all occurrences of newline (\n) with <br/> re.sub('\r?\n', '<br/>', some_text) # replace only the first 3 occurrences re.sub('\r?\n', '<br/>', some_text, 3) # replace with value from match group re.sub(r'Value: "(.*)"', r'\1', 'Value: "the value"')
Easy email testing with http://www.ximailstop.com