【问题标题】:Does an if re match & group capture in the same line?if re 匹配和组捕获是否在同一行中?
【发布时间】: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

这似乎必须进行两次匹配。

【问题讨论】:

    标签: python python-re


    【解决方案1】:

    只需删除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
    

    【讨论】:

    • 完美,谢谢,这正是我所追求的。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    • 2022-09-28
    • 1970-01-01
    • 2017-10-08
    • 2015-04-03
    • 1970-01-01
    • 2021-06-21
    相关资源
    最近更新 更多