Dear Monks,

Perhaps I'm not seeing the obvious mistake in my regexp-code, but I think I found some strange behavior of the regexpr engine:

wine@localhost]$ perl -pe 's/(")[^\1]*\1/check/g' "strings 1" "string 2" # input check #output

I hope you'll agree this is wrong. It should yield: check check. If you transscribe the expression by removing the backreferences you get the normal behavior:

wine@localhost]$ perl -pe 's/"[^"]*"/check/g' "string 1" "string 2" check check

Using $1 yields:

wine@localhost]$ perl -pe 's/(")[^$1]*$1/check/g' "string 1" "string 2" Unmatched [ before HERE mark in regex m/(")[ << HERE ^]*/ at -e line 1 +, <> line 1.

This isn't related to the ". It doesn't work with normal alpha-characters either:

wine@localhost]$ perl -pe 's/(a)[^\1]*\1/check/g' abbbba abbbbbbbba check

Using a | helps if the two side differ:

# ("|'"'"') is a complex bash escape for ("|') wine@localhost]$ perl -pe 's/("|'"'"')[^\1]*\1/check/g' "aaa" 'aaa' check check

But if you use differt input it goes wrong again, and this should really not happen:

perl -pe 's/("|'"'"')[^\1]*\1/check/g' "aaa" "aaa" check

Can someone explain this behavior. (").*?\1 seems to work, but is not compliant with lets say sed, which seems to have the same problem:

wine@localhost]$ sed 's/\(a\)[^\1]*\1/check/g' abbbba abbbbbbbba check

Thank you in advance

wine


In reply to Strange regexp behavior by wine

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.