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 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)
18
задан Rick 19 August 2010 в 07:02
поделиться

3 ответа

>>> 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'

Редактировать: Документы Python могут быть весьма полезным справочником.

19
ответ дан 30 November 2019 в 08:42
поделиться
>>> import re
>>> regex = re.compile(r".*?var:(.*?);")
>>> regex.sub(r"\1test", "fksf var:asfkj;")
'asfkjtest'
7
ответ дан 30 November 2019 в 08:42
поделиться

Документация python находится в сети, а документ для модуля re находится здесь. http://docs.python.org/library/re.html

Однако, чтобы ответить на ваш вопрос, Python использует \ 1 вместо $ 1 для ссылки на совпадающие группы.

-3
ответ дан 30 November 2019 в 08:42
поделиться
Другие вопросы по тегам:

Похожие вопросы: