if重新匹配和组捕获是否在同一行中?

2024-09-24 00:24:30 发布

您现在位置:Python中文网/ 问答频道 /正文

Python中有没有一种方法可以进行if重新匹配&;组捕获在同一行中

在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

这场比赛似乎要进行两次


Tags: 方法reifabmatchlinescriptscd
1条回答
网友
1楼 · 发布于 2024-09-24 00:24:30

只需删除search。你不需要它

matches = re.findall('ab(.*)ef', line)
print(matches)

或者,如果您只对第一个匹配感兴趣,请删除findall

match = re.search('ab(.*)ef', line)
if match:
    print(match.group(1)) # 0 is whole string, 1 is first capture

相关问题 更多 >