mkHun mkHun - 4 months ago 8
Perl Question

Is there any possible way to match the n'th character?

My input data as below. I want to group the word between the 6th and 7th position of the

-
.

my $sa = "a1a1a1-b1b1b1-c-ddd-eee-fff-gggggg-hHhH-iiii-j-KKKKK";


For this, the actual regex was

/[^-]+-[^-]+-[^-]+-[^-]+-[^-]+-([^-]+)-/


For to build the regex, I tried as below,

my $avc = "[^-]+-" x 5 . "([^-]+)-";

my $ar = qr"$avc";

$sa =~m/$ar/g;

print $1;


My doubt, Is there any options are available for within regex. Without using
x
. How can I do it in a single regex?

Answer

Use limiting repetition quantifier

/(?:[^-]+-){5}([^-]+)-/

Regular expression visualization

Regex explanation here.


The capturing group can be within the repetitive group only the last one gets captured.

/(?:([^-]+)-){6}/

Regular expression visualization

Regex explanation here.