Link to home
Start Free TrialLog in
Avatar of Tolgar
Tolgar

asked on

How to remove a string from a longer string in Perl?

Hi,
I would like to replace the following from a longer string.

<td >
/some/path/to/a/file/fileA.x  [<a href="special:read('/some/path/to/a/file/fileA.x')">Open</a>]
</td>

Open in new window


/some/path/to/a/file/fileA.x is a dynamic file name and it is comes from $file in the code. Then rest is static.

Can you please tell me how I should write the regexp?

So, the pattern is like this:


<td >
$file  [<a href="special:read('$file')">Open</a>]
</td>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Terry Woods
Terry Woods
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I'd do it like this:
my $str = "<td >\n$file  [<a href="special:read('$file')">Open</a>]\n</td>";
unless ($long_string =~ s{$text_to_replace}{$str}ms) {
    # or $long_string =~ s{$str}{$text_to_replace_with}ms - I'm not clear which you want
    print "no match found\n";
}

Open in new window

@wilcoxon, won't any . characters in the string be treated as wildcards without escaping? (and other characters such as [](){}*+? may affect the pattern too)
Avatar of Tolgar
Tolgar

ASKER

Perfect!!
Probably.  If so, it's simple to just stick \Q at the beginning of the regex (don't remember if \Q$str will work or if \Q needs to be inside $str at the beginning).
\Q$str\E will quote metacharacters