Regex: How to escape + sign?

V

Vito Corleone

Hi,

How can I escape + sign from regex? I want to change:
C++ to <b>C++</b>

Here is what I did:
#!/usr/bin/perl
$text = "C++";
$source = "Perl c++ c-- Java C-- C++";
$source =~ s#$text#<b>$text</b>#ig;
print $source . "\n";

[bk@wolverine bk]$ ./test.pl
Nested quantifiers in regex; marked by <-- HERE in m/C++ <-- HERE / at
../test.pl line 4.

How can I do that? Plese help.

--Vito
 
J

J. Romano

Vito Corleone said:
How can I escape + sign from regex?

Here is what I did:

$text = "C++";
$source = "Perl c++ c-- Java C-- C++";
$source =~ s#$text#<b>$text</b>#ig;

Vito,

Another way to do that is to change the line:

$text = "C++";

to:

$text = quotemeta("C++");

This will escape all non-alphanumeric characters so that the '+'
signs will match only to '+' signs if placed in a regular expression.
You can even print out $text after you set it to see what it looks
like -- it might help you understand what is happening.

-- Jean-Luc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top