Python: global replacement with regex 

Joined:
04/09/2007
Posts:
727

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"')
Share |
| Comment  | Tags
 
Easy email testing with http://www.ximailstop.com