Skip to content Skip to sidebar Skip to footer

Python Regex, Re.sub, Replacing Multiple Parts Of Pattern?

I can't seem to find a good resource on this.. I am trying to do a simple re.place I want to replace the part where its (.*?), but can't figure out the syntax on how to do this.. I

Solution 1:

>>> import re
>>> originalstring = 'fksf var:asfkj;'
>>> pattern = '.*?var:(.*?);'
>>> pattern_obj = re.compile(pattern, re.MULTILINE)
>>> replacement_string="\\1" + 'test'
>>> pattern_obj.sub(replacement_string, originalstring)
'asfkjtest'

Edit: The Python Docs can be pretty useful reference.


Solution 2:

>>> import re
>>> regex = re.compile(r".*?var:(.*?);")
>>> regex.sub(r"\1test", "fksf var:asfkj;")
'asfkjtest'

Post a Comment for "Python Regex, Re.sub, Replacing Multiple Parts Of Pattern?"