Reputation: 4084
I am trying to make a perl regex that references something it finds in the query on the fly. I've never tried to make a regex like this, and am not even sure it is possible. Here's my current regex:
$sample =~ s/(+|-)[1][a-zA-Z]{1}//g;
This is meant to take my $sample
variable as a query, and delete any section of the string that matches something like +1X
with nothing. However, the number defines the number of following characters, all of which I want removed.
So, if my string is foo+3xzybar
, the regex should return foobar
. How can I grab the matching number in the regex and use it to quantify the number of letters to match? Instead of writing explicit cases like this:
$sample =~ s/(+|-)[1][a-zA-Z]{1}//g;
$sample =~ s/(+|-)[2][a-zA-Z]{2}//g;
$sample =~ s/(+|-)[3][a-zA-Z]{3}//g;
$sample =~ s/(+|-)[4][a-zA-Z]{4}//g;
I want to make something like this:
$sample =~ s/(+|-)[(0-9)][a-zA-Z]{($1)}//g; #(0-9) is meant to match and save the digit in $1
Any help is appreciated!
Upvotes: 1
Views: 161
Reputation: 2233
When one is willing to use fancy (and experimental) Perl RE features, the (??{ code })
extended pattern works:
$sample =~ s/[+-](\d)(??{ "[a-zA-Z]{$1}" })//g
Upvotes: 1
Reputation: 5083
I would probably use a match to breakup the string, and then reassemble it a line later:
$sample =~ /(.*?)[+\-]([0-9])([a-zA-Z]+)(.*)/ ;
$sample= $1 . substr($3, $2) . $4 if $2 ;
So you get everything before the +N, then use +N to offset into the letters right beyond, then tack anything else on afterwards. Repeat as necessary.
Upvotes: 2