Regex: How to escape + sign?

Discussion in 'Perl Misc' started by Vito Corleone, Feb 10, 2004.

  1. 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
     
    Vito Corleone, Feb 10, 2004
    #1
    1. Advertising

  2. Vito Corleone wrote:
    > How can I escape + sign from regex?

    ------------^^^^^^

    <snip>

    > $source =~ s#$text#<b>$text</b>#ig;


    Try:

    $source =~ s#\Q$text#<b>$text</b>#ig;
    -----------------^^

    --
    Gunnar Hjalmarsson
    Email: http://www.gunnar.cc/cgi-bin/contact.pl
     
    Gunnar Hjalmarsson, Feb 10, 2004
    #2
    1. Advertising

  3. On Tue, 10 Feb 2004 11:37:44 +0100
    Gunnar Hjalmarsson <> wrote:

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

    > ------------^^^^^^
    >
    > <snip>
    >
    > > $source =~ s#$text#<b>$text</b>#ig;

    >
    > Try:
    >
    > $source =~ s#\Q$text#<b>$text</b>#ig;
    > -----------------^^


    Wow, it works! Thanks Gunnar :)

    --Vito
     
    Vito Corleone, Feb 10, 2004
    #3
  4. Vito Corleone

    J. Romano Guest

    Vito Corleone <> wrote in message news:<>...

    > 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
     
    J. Romano, Feb 11, 2004
    #4
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Tassos

    escape a whole regex

    Tassos, Dec 12, 2003, in forum: Perl
    Replies:
    2
    Views:
    532
    Jim Gibson
    Dec 12, 2003
  2. Jimmy
    Replies:
    1
    Views:
    970
    Cowboy \(Gregory A. Beamer\)
    Nov 21, 2006
  3. slomo
    Replies:
    5
    Views:
    1,603
    Duncan Booth
    Dec 2, 2007
  4. Replies:
    3
    Views:
    807
    Reedick, Andrew
    Jul 1, 2008
  5. Jimmy
    Replies:
    3
    Views:
    2,438
    shimmyshack
    Nov 20, 2006
Loading...

Share This Page