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

Ian*_*des 5 python perl

我有/VA=\d+:(\S+):ENSG/一个在if语句中使用的perl正则表达式

if ($info =~ /VA=\d+:(\S+):ENSG/){
    $gene =$1;
Run Code Online (Sandbox Code Playgroud)

我试图弄清楚在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)]
Run Code Online (Sandbox Code Playgroud)

这是翻译它的好方法吗?我想这是perl实际上比python更具可读性的一个领域.

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

unu*_*tbu 3

你可以使用

gene = this_re.group(1)
Run Code Online (Sandbox Code Playgroud)

代替

gene = info[this_re.start(0):this_re.end(0)]
Run Code Online (Sandbox Code Playgroud)

顺便说一句,Pythonre模块会缓存N最近使用的正则表达式模式,因此(除非您有大量模式)无需预编译它。

对于 Python 2.7,re._MAXCACHE(即N) 为 100。