18

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 know how to do it in PHP, so I've been messing around with what I think it could be based on that (which is why it has the $1 but I know that isn't correct in python).. I would appreciate if anyone can show the proper syntax, I'm not asking specifics for any certain string, just how I can replace something like this, or if it had more than 1 () area.. thanks

originalstring = 'fksf var:asfkj;'
pattern = '.*?var:(.*?);'
replacement_string='$1' + 'test'
replaced = re.sub(re.compile(pattern, re.MULTILINE), replacement_string, originalstring)
2
  • 1
    Can you give an example of exactly what you'd like the resulting string to be? Is it asfkjtest?
    – mikej
    Aug 19, 2010 at 7:12
  • its just for an example, doesn't really matter what its for, I have a lot of regex stuff I did in php that I'm not trying to do in python so I just need to get the idea of how to do it down
    – Rick
    Aug 19, 2010 at 7:21

3 Answers 3

19
>>> 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.

4
  • 6
    I know, I don't know why this is mentioned by everyone (about the python docs), I already know about these and have looked through them, I am posting here since I am still not clear on how to do this after consulting this, Python doesn't seem to be like PHP where it has a number of other resources on a topic like this so, after more searching, I felt I should post here (I'm not criticizing python for this, as I love it, its just an observation)
    – Rick
    Aug 19, 2010 at 7:19
  • anyways, thanks for the help in posting the example, I do appreciate it
    – Rick
    Aug 19, 2010 at 7:20
  • Oops, I didn't see that. Glad I could help!
    – Umang
    Aug 20, 2010 at 7:10
  • 2
    Actually using a raw string allows you to use a single slash r'\1'
    – topdog
    Mar 11, 2012 at 6:18
7
>>> import re
>>> regex = re.compile(r".*?var:(.*?);")
>>> regex.sub(r"\1test", "fksf var:asfkj;")
'asfkjtest'
-2

The python docs are online, and the one for the re module is here. http://docs.python.org/library/re.html

To answer your question though, Python uses \1 rather than $1 to refer to matched groups.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.