Does an if re match & group capture in the same line?

Viewed 84

Is there a way in Python to do an if re match & group capture in the same line?

In PERL I would do it like this:

my $line = "abcdef";

if ($line =~ m/ab(.*)ef/) {
    print "$1\n";
}

output:

badger@pi0: scripts $ ./match.py
cd

but the closest way I can find in Python is like this:

import re

line = 'abcdef'

if re.search('ab.*ef', line):
    match = re.findall('ab(.*)ef', line)
    print(match[0])

output:

badger@pi0: scripts $ ./match.pl
cd

which would seem to have to do the match twice.

1 Answers

Just remove the search. You don't need it.

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

Or if you're only interested in the first match, remove the findall:

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