in reply to Regexp: How to match in middle but not the ends?

Don't use $&! It slows down all the regexp in your program (including modules) that don't have captures. Use captures instead.
while ($string =~ /([CSH][CSHL]*[CSH])/g) { print "$1, "; }

Use join to avoid the trailing comma.

print join ', ', $string =~ /([CSH][CSHL]*[CSH])/g;

An alternative approach would be to strip out the offending L characters.

for ($string) { s/-L+|L+-/-/g; s/^L+//; s/L+$//; print join ', ', /([CSHL]{2,})/g; }

Update: Added s/^L// and s/L$//.
Update: Changed L to L+.
Update: Accidently changed too many things to "+"s. Fixed.

Replies are listed 'Best First'.
Re^2: Regexp: How to match in middle but not the ends?
by Skeeve (Parson) on Jul 30, 2006 at 16:59 UTC
    If you strip the L, don't forget (like I did first) to strip an L at the start and end of the string. You should also use "+" to strip any sequence of L. I think, this will do: s/(?:^L+)|(?:-L+)|(?:L+-)|(?:L+$)/-/g (I used (?:) because I'm currently too busy (lazy) to test...

    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e

      No, he shouldn't use "+", since he doesn't want to strip any sequence of "L". For example, your solution fails to match "LL" in "---LLLL---".

      My solution was lacking since I wasn't checking for an L at the start or end of the string. Fixes:

      $string =~ s/-L|L-/-/g; $string =~ s/^L//; $string =~ s/L$//;
      or
      $string =~ s/^L|(?<-)L|L(?=-)|L$//g;
      or
      # Does a bit more than stripping, but in an inconsequential fashion. $string =~ s/^L|-L|L-|L$/-/g;

        It's debatable: The OP said, the strings may not start or end with L. He didn't say which strings: Those, that are returned (use +) or those that are found (don't use +).

        I vote for the strings returned ;-) But only the OP can tell.

        P.S. See his (partial) Solution, He's cutting of all leading L's, so I have a good argument for my view, don't you agree?


        s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
        +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
Re^2: Regexp: How to match in middle but not the ends?
by Hofmator (Curate) on Jul 31, 2006 at 11:08 UTC
    print join ', ', $string =~ /([CSH][CSHL]+[CSH])/g;
    matches at least 3 characters and thus should be print join ', ', $string =~ /([CSH][CSHL]*[CSH])/g; (as you mention somewhere else in this thread).

    -- Hofmator