I need to replace some metachars ? => # and * => ? but only if they are unescaped and at the same time unescape all escaped chars.
I first tried many variations with a couple of substitutions but none of them worked. At last I found something that works but looks somewhat odd:
my $string = 't?e\\\\xt\\\\* with escapes\\*'; my $result = ''; while (not $string =~ m/\G\z/gc) { if ($string =~ /\G([^\\*?]+)/gc) { # normal chars $result .= $1; } elsif ($string =~ /\G\\(.)/gc) { # escaped $result .= $1; } elsif ($string =~ /\G\*/gc) { # unescaped * $result .= '?'; } elsif ($string =~ /\G\?/gc) { # unescaped ? $result .= '#'; } } $string = $result; print $string; # prints 't#e\xt\? with escapes*'
As I said I can live with it but I wonder if there is also a solution based on a couple of s///g; It is somewhat embarrassing not to find a solution for such a seemingly simple problem. So I hope for your wisdom to learn and improve my regex arsenal.

Thanks
Michael

In reply to Replace only unescaped metachars by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.