【发布时间】:2020-05-28 10:20:36
【问题描述】:
在 Python 中有没有办法在同一行中进行 if re match & group 捕获?
在 PERL 中我会这样做:
my $line = "abcdef";
if ($line =~ m/ab(.*)ef/) {
print "$1\n";
}
输出:
badger@pi0: scripts $ ./match.py
cd
但我在 Python 中能找到的最接近的方法是这样的:
import re
line = 'abcdef'
if re.search('ab.*ef', line):
match = re.findall('ab(.*)ef', line)
print(match[0])
输出:
badger@pi0: scripts $ ./match.pl
cd
这似乎必须进行两次匹配。
【问题讨论】: