Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re^3: Regex in json: escaping forward slash

by davido (Cardinal)
on Aug 22, 2012 at 21:38 UTC ( [id://989155]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Regex in json: escaping forward slash
in thread Regex in json: escaping forward slash

But what's the problem? Maybe you could provide an example of how your code is failing to deal with '/' properly. In the following example I decode your sample JSON, grab the key that looks like a regular expression, compile it as a regular expression, and use it to perform a match.

use strict; use warnings; use JSON; use constant KEY => 0; use constant VALUE => 1; my $json_string = <<'END_JSON'; { "regex" : { ".*/home/members/index.htm.*" : { "404" : { "reporting" : "1000", "paging" : "2000" } } } } END_JSON my @test_strings = qw( web/home/members/index.htm?garbage=bye /home/memberzzzz/index.htm?garbage=bye ); my $decoded_json = JSON->new->decode( $json_string ); # The regex is contained within a hash key. my $regex_string = (%{$decoded_json->{regex}})[KEY]; my $regex = qr/$regex_string/; foreach my $test_string ( @test_strings ) { if( $test_string =~ m/$regex/ ) { print "Bingo! [$test_string] matches the pattern '$regex_string'\n +"; } else { print "Boo! [$test_string] doesn't match the pattern '$regex_strin +g'\n"; } }

No special escaping of '/' here. The qr// operator is convenient.


Dave

Replies are listed 'Best First'.
Re^4: Regex in json: escaping forward slash
by mhearse (Chaplain) on Aug 22, 2012 at 23:37 UTC
    Thanks for your reply. I made a poor assumption. I was under the impression that:
    my $regex = ".*/home/members/index.htm.*"; if (/$regex/)
    Was the same as
    if (/.*/home/members/index.htm.*/)
    Which would fail. I was wrong!

      perlop (Gory Details of Parsing Quoted Constructs): "The most important Perl parsing rule is the first one discussed below: when processing a quoted construct, Perl first finds the end of that construct, then interprets its contents."

      m// is a quoted construct. So the "end" will be found before the contents are interpreted (including interpolated). Now if you say, "m/a/b/", the problem is that the end is found between 'a' and 'b'. But when you say, $c='/', and then m/a${c}b/, the end is found after 'b', and later the interpolation of $c takes place.


      Dave

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://989155]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (2)
As of 2024-04-19 21:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found