Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

matching a "regex" expression

by slugger415 (Beadle)
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

Comment on matching a "regex" expression
Select or Download Code
Re: matching a "regex" expression
by kennethk (Monsignor) 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.

    CountZero

    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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://976010]
Approved by cavac
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2014-09-01 23:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (18 votes), past polls