perl regular expressions substitution/replacement using variables with special characters
Posted
by
user961627
on Stack Overflow
See other posts from Stack Overflow
or by user961627
Published on 2012-04-06T13:32:33Z
Indexed on
2012/04/06
17:29 UTC
Read the original article
Hit count: 215
Okay I've checked previous similar questions and I've been juggling with different variations of quotemeta but something's still not right.
I have a line with a word ID and two words - the first is the wrong word, the second is right. And I'm using a regex to replace the wrong word with the right one.
$line = "ANN20021015_0104_XML_16_21 A$xAS A$xASA";
@splits = split("\t",$line);
$wrong_word = quotemeta $splits[1];
$right_word = quotemeta $splits[2];
print $right_word."\n";
print $wrong_word."\n";
$line =~ s/$wrong_word\t/$right_word\t/g;
print $line;
What's wrong with what I'm doing?
Edit
The problem is that I'm unable to retain the complete words - they get chopped off at the special characters. This code works perfectly fine for words without special characters.
The output I need for the above example is:
ANN20021015_0104_XML_16_21 A$xASA A$xASA
But what I get is
ANN20021015_0104_XML_16_21 A A
Because of the $
character.
© Stack Overflow or respective owner