user2886545
user2886545

Reputation: 713

Perl - Regex and matching variables

Good morning guys,

I have the following code:

$line =~ s/gene_id "([A-Za-z0-9:\-._]*_[oO])([_.])[0-9]*";/gene_id "$1$21";/g;

And I have problems with $1 and $2. I want the output to be $1$21, in other words, $1 and $2 and 1, all together. However, Perl sees $21 instead of $2 and 1. How would I avoid this problem?

Thanks.

Upvotes: 2

Views: 73

Answers (1)

Miller
Miller

Reputation: 35208

Use braces around your variable identifier to isolate it from surrounding text, ${2}

$line =~ s/gene_id "([A-Za-z0-9:\-._]*_[oO])([_.])[0-9]*";/gene_id "$1${2}1";/g;

Also, since you're keeping all other text the same, you could just use \K to only modify what comes after it. Not to mention utilizing \w to reduce your first character class:

$line =~ s/gene_id "[\w:\-.]*_[oO][_.]\K[0-9]*";/1";/g;

Upvotes: 3

Related Questions