Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

matching a "regex" expression

by slugger415 (Scribe)
on Jun 13, 2012 at 16:46 UTC ( #976010=perlquestion: print w/replies, xml ) Need Help??
slugger415 has asked for the wisdom of the Perl Monks concerning the following question:

Hello esteemed monks, I am having trouble with a regex match on a string that contains a regex. I've not figured out how to match on it. This string appears in an HTML page:

document.write(this.location.href.replace(/\?resultof.*$/i, ''));

I need to find and replace it with something else, but I can't seem to match all those regex characters as literals. I've tried replacing all the parens, question marks, etc.

$j =~ s/\\/\\\\/g; $j =~ s/\?/\\\?/g; $j =~ s/\$/\\\$/g; $j =~ s/\*/\\\*/g; $j =~ s/[.]/\\./g; $j =~ s/[)]/\\\)/g; $j =~ s/[(]/\\\(/g;

any thoughts from the experts? thanks

Replies are listed 'Best First'.
Re: matching a "regex" expression
by kennethk (Abbot) on Jun 13, 2012 at 17:11 UTC
    If you need to match a string literal that contains regular expression metacharacters, you can make sure to get the escaping right using either quotemeta or the \Q ... \E delimiters, as described in Quote and Quote like Operators. A working example:

    my $regex = quotemeta q{document.write(this.location.href.replace(/\?r +esultof.*$/i, ''));}; my $j =~ s/$regex/something else/;

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

      thank you (both) that's just what I was looking for.

Re: matching a "regex" expression
by CountZero (Bishop) on Jun 13, 2012 at 17:14 UTC
    use the quotemeta function on your string or put the string inside \Q and \E in the regex.


    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

    My blog: Imperial Deltronics
""regex" expression" - another example of "NIC card" or "ATM machine" usage
by parv (Priest) on Jun 14, 2012 at 08:15 UTC
    "Regex" (or "regexp") stands for "regular expression". Avoid useless duplication.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://976010]
Approved by cavac
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2018-01-21 13:48 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (228 votes). Check out past polls.