in reply to Matching backslash in regexp negative lookbehind

#!/usr/bin/perl -l # http://perlmonks.org/?node_id=1206551 use strict; use warnings; my $param = 'password'; for ( q~{'password' => 'secret'}~, q~{"password" => "sec\"ret"}~ ) { local $_ = $_; s/ ( # capture everything up to the start of th +e value ( # capture the quotation mark we are usin +g (?<!\\\\) # not escaped [ ' " ] # either kind of quote ) # end capture quotation mark $param # the key \2 # the same quotation mark \s* # any amount of space (?: => | : ) # perl or JSON key-value "connector" \s* # any amount of space \2 # the same quotation mark ) # end capture everything up to start of th +e value (?: # group but do not capture the value \\. | (?!\2) . # defined as any character except the same + quote )* # any number of times /$1***/smxg; # the closing quotation mark will remain i +n place print $_; }

Outputs:

{'password' => '***'} {"password" => "***"}

Replies are listed 'Best First'.
Re^2: Matching backslash in regexp negative lookbehind
by AnomalousMonk (Archbishop) on Jan 02, 2018 at 20:03 UTC
    [ ' " ]           # either kind of quote

    Note that  [ ' " ] also matches a blank (0x20). Better perhaps to use  ['"] instead.


    Give a man a fish:  <%-{-{-{-<

      Yes. But there's another possibility: - quoting Regexp Quote-Like Operators in perlop:
      x   Use extended regular expressions;
      specifying two x's means \t and the SPACE character are ignored within square-bracketed character classes

        Forgot about that. I'm not really up on the latest regex extensions. Offhand, do you know with what Perl version the  xx modifier modification was added?


        Give a man a fish:  <%-{-{-{-<

Re^2: Matching backslash in regexp negative lookbehind
by 1nickt (Canon) on Jan 02, 2018 at 19:14 UTC

    I am in awe of the effortless boxlessness of your mind.

    Thank you very much.


    The way forward always starts with a minimal test.