user1461988
user1461988

Reputation: 3

How to get the expression of matching capture in Perl

In Perl, how can I get the expression of a capture that has matched in a regex?

$s = 'aaazzz';
$s =~ s/(a+)|(b+)|(c+)/.../;
$s =~ s/(?<one>a+)|(?<two>b+)|(?<three>c+)/.../;

I mean the expression (e.g. a+), not the string aaa.

I need the expression of both numbered and named captures.

Upvotes: 0

Views: 141

Answers (2)

Toto
Toto

Reputation: 91385

I'd do something like:

use strict;
use warnings;

my @regexes = (
    qr/(a+)/,
    qr/(b+)/,
    qr/(c+)/,
);
my $string = 'aaazzz';
foreach my $re(@regexes) {
    if ($string =~ $re) {
        print "Used regex is $re\n";
    }
}

Output:

Used regex is (?^:(a+))

Upvotes: 1

Kim Ryan
Kim Ryan

Reputation: 515

You could assemble your regex from components and then test which groups matched. For demo purposes, I have only used match and not match and the replace operator 's', but same principle applies.

$s = 'aaazzz';
$part1 = '(a+)';
if ( $s =~ /$part1|(b+)|(c+)/ ) {

    if ($1) {
        print("$part1 matched\n");
    }
    else {
        print("$part1 did not match\n");
    }
}

Upvotes: 0

Related Questions