in reply to Why my Regex doesn't work

A \n regex backreference is not active in a character class;  [^\1] is equivalent to  [^1]   (Update: Nope. Not quite. See Update below.)

Try:

c:\@Work\Perl\monks>perl -wMstrict -le "my $s = 'CCHHHCHHCHC'; print qq{'$s'}; ;; $s =~ s/(\w) (?!\1). \1/$1$1$1/xgi; print qq{'$s'}; " 'CCHHHCHHCHC' 'CCHHHHHHHHC'
(note the use of the  /x modifier — for clarity only).

Update: In fact,  \1 in a character class is an octal escape sequence:

c:\@Work\Perl\monks\flappygoat>perl -wMstrict -le "my $s = qq{\1\x01\o{001}\cA}; print 'match' if $s =~ /[^\1]/; print 'count: ', $s =~ tr/\1//; " count: 4
(no match; nothing printed). Wonderful what you can find out if you actually test stuff.


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

Replies are listed 'Best First'.
Re^2: Why my Regex doesn't work
by Anonymous Monk on Apr 11, 2017 at 15:28 UTC
    The OP wanted CCHHHHHHHCC, not CCHHHHHHHHC. Maybe that's a typo, or maybe he wants all the surrounded characters substituted simultaneously, as in a cellular automaton. In that case,
    s/(?<=(\w))(?!\1).(?=\1)/$1/g;

      Yeah. The problem seems underspecified.

      For example, what output would the OP want from CHCHC?

      AnomalousMonk's snippet outputs CCCHC, while anonymonk's gives CCHCC...

      thank you so much! That is exactly what I needed. I wonder tho if it's possible to do without "lookaround".
        I wonder tho if it's possible to do without "lookaround".

        There is probably some tricky way to avoid lookarounds, but just as a matter of curiosity, why would you want to? Lookarounds have been a part of Perl 5 regex from the beginning. Was it only a matter of curiosity on your part?


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

Re^2: Why my Regex doesn't work
by flappygoat (Initiate) on Apr 11, 2017 at 17:34 UTC
    Thank you. That is what I was trying to code even tho I see now that it has a problem, it won't match the last 3 chars CHC, but the other comment solved it.