翻译perl正则表达式时选择哪个python re模块

翻译perl正则表达式时选择哪个python re模块,python,perl,Python,Perl,我有perl正则表达式/VA=\d+:(\S+):ENSG/,它在if语句中用作 if ($info =~ /VA=\d+:(\S+):ENSG/){ $gene =$1; 我正试图找出在python中复制此功能的最佳方法。现在我有 gene_re = re.compile(r'VA=\d+:(\S+):ENSG') this_re = re.search(gene_re, info) if this_re is not None: gene = info[this_re.st

我有perl正则表达式
/VA=\d+:(\S+):ENSG/
,它在if语句中用作

if ($info =~ /VA=\d+:(\S+):ENSG/){
    $gene =$1;
我正试图找出在python中复制此功能的最佳方法。现在我有

gene_re = re.compile(r'VA=\d+:(\S+):ENSG')
this_re = re.search(gene_re, info)
if this_re is not None:
    gene = info[this_re.start(0):this_re.end(0)]
这是翻译它的好方法吗?我想这是perl实际上比python更具可读性的一个领域

请注意,编译python正则表达式是因为接下来的三行实际上在一个循环中。

您可以使用

gene = this_re.group(1)
而不是

gene = info[this_re.start(0):this_re.end(0)]

顺便说一下,Python
re
模块缓存最近使用的regex模式,因此(除非您有大量的模式),不需要预编译它


对于Python2.7,
re.\u MAXCACHE
(即
N
)是100。

我不知道关于重新缓存的这一点非常酷。有一个问题——它不应该是组(0)而不是组(1)?即使Python使用基于0的索引,正则表达式组也从1开始编号。所以它是
组(1)
。这与使用
re.sub
时引用第1组匹配的
r'\1'
一致。从解释器:>>p=re.match('a','aa')>>p.group(0)'a'如果
p=re.match('(a)(b)'ab')
,那么
p.group(0)
'ab'
,而
p.group(1)
a
。您需要
p.group(1)
<代码>组(0)是整个匹配,
组(1)
是第一个括号中的匹配。请参阅。如果不存在此项,则不需要
。在python中,如果这是:
,通常只会说
。我被教导使用的不是None,因为它更清晰,而且因为None!=假的