我刚刚从 Perl 切换到 Python,对re模块感到失望。我正在寻找 Python 中的 $1 等价物,或正则表达式中的任何其他特殊变量。在 Perl 中我会使用这个:
我正在尝试在 Python 中做同样的事情。谢谢!
$_ =
"<name>Joe</name>";
s/<(.)>(.)<[/]
(.*)>/$2/;
2 回答
You can also use the \2
in the back ref or match group in Python.
Such as this:
>>> re.sub(r'(\w+) (\w+)',r'\2 \1','Joe Bob')
'Bob Joe'
Or named substitutions (a Python innovation later ported to Perl):
>>> re.sub(r'(?P<First>\w+) (?P<Second>\w+)',r'\g<Second> \g<First>','Joe Bob')
'Bob Joe'
>>> ma=re.search(r'(?P<First>\w+) (?P<Second>\w+)','George Bush')
>>> ma.group(1)
'George'
>>> ma.group('Second')
'Bush'
But, admittedly, Python re module is a little weak in comparison to recent Perl's.
For a first class regex module, install the newer regex module. It is scheduled to by part of Python 3.4 and is very good.
You want the re.MatchObject.group() method.
import re
var = "<name>Joe</name>"
match = re.search(r"<(.)>(.)<[/](.*)>", var)
print match.group(2)
It looks like you are using regex to parse a tag-based markup language such as XML. See the following link on why you should use a parser such as ElementTree instead: https://stackoverflow.com/a/1732454/1032785