I have the following string :
Cat dog fox catepillar bear foxy
I need to replace "cat" and "fox" words from this sentence to word "animal"
I do the following:
$Str1="cat";
$Str2="fox";
$NewStr="animal";
open(F1, "<$inputFile") or die "Error: $!";
open(F2, ">$outputFile") or die "Error: $!";
while ($line = <F1>) {
$line =~ s/$Str1|$Str2/NewStr/g;
print F2 "$line";
}
But the problem that word's "catepillar" and "foxy" parts("cat" and fox) also are replaced. How to replace only words "cat" and "fox"?
Use a word boundary assertion to build your regex. You can find information on it at http://perldoc.perl.org/perlre.html.
There's a couple more problems here.
What the changes mean:
\b
zero width assertion for a word boundary(?:
start a group but don't use it for capturing, just grouping