Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I have a string that can have the form:
$str = 'LLLLLLLLLLLLLLLLLLLOOOOOOOOOOOOO';
or
$str = 'LLLLLLLLLLCOOOOOOOOOOOOOOOOOOOOOO';

I wrote this reg exp, but it does not seem to work:
if($str=~/^(L+)/ or $str=~/^(L+C)/)

Can you tell me why? I would like it that it can catch both possibilities, either being LO or LCO and I thought this or was what I needed, but it does not work and it fails for both.
Thanks

Replies are listed 'Best First'.
Re: Regular expressions mystery
by soonix (Chancellor) on Jul 01, 2018 at 13:31 UTC
    you might want to match /^(L+C?)/ .
    Another way: if it isn't possible to combine it into a single regex, change the order of the conditions such that the longer comes earlier.
Re: Regular expressions mystery
by Lotus1 (Vicar) on Jul 01, 2018 at 12:53 UTC

    It 'worked' for me. You might want to let us know what you are trying to capture or accomplish and show a complete program.

    use warnings; use strict; foreach my $str ( 'LLLLLLLLLLLLLLLLLLLOOOOOOOOOOOOO', 'LLLLLLLLLLCOOOO +OOOOOOOOOOOOOOOOOO' ){ if($str=~/^(L+)/ or $str=~/^(L+C)/) { print "matched '$1'\n"; } } __END__ matched 'LLLLLLLLLLLLLLLLLLL' matched 'LLLLLLLLLL'

      AnonyMonk:   Note that you will never capture the  C character in the string (if this is what you want to do) because the  $str =~ /^(L+)/ expression will always match first in
          if ($str =~ /^(L+)/ or $str =~ /^(L+C)/) { ... }
      for the strings you give as examples. If you want the  C captured, reverse the order of the matches
          if ($str =~ /^(L+C)/ or $str =~ /^(L+)/) { ... }
      or much better yet IMHO, just use a single regex with an optional  C match
          if ($str =~ /^(L+C?)/) { ... }
      (See the  ? quantifier in perlre.)


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

        Thank you very much! Good point
Re: Regular expressions mystery
by Anonymous Monk on Jul 01, 2018 at 11:17 UTC
    Aha, it should have been | instead of or. I did not know that.
      Aha, it should have been | instead of or. I did not know that.
      What makes you say that? | is a "bitwise or" which isn't of any benefit here. or is quite fine!