Python Regex,re.sub,替换模式的多个部分?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3519487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:31:35  来源:igfitidea点击:

Python Regex, re.sub, replacing multiple parts of pattern?

pythonregex

提问by Rick

I can't seem to find a good resource on this.. I am trying to do a simple re.place

我似乎找不到这方面的好资源..我正在尝试做一个简单的 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

我想替换它的 (.*?) 部分,但无法弄清楚如何做到这一点的语法..我知道如何在 PHP 中做到这一点,所以我一直在搞乱我的想法可能基于此(这就是为什么它有 $1,但我知道这在 python 中是不正确的)。如果有人可以显示正确的语法,我将不胜感激,我不是在询问任何特定字符串的细节,只是如何我可以替换这样的东西,或者如果它有超过 1 () 个区域..谢谢

originalstring = 'fksf var:asfkj;'
pattern = '.*?var:(.*?);'
replacement_string='' + 'test'
replaced = re.sub(re.compile(pattern, re.MULTILINE), replacement_string, originalstring)

采纳答案by Umang

>>> 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 Docscan be pretty useful reference.

编辑:Python Docs是非常有用的参考。

回答by Rick

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

python 文档在线,re 模块的文档在这里。http://docs.python.org/library/re.html

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

不过,为了回答您的问题,Python 使用 \1 而不是 $1 来引用匹配的组。

回答by Daniel Kluev

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