in reply to Regex question

If you use a regex, you're going to have to quotemeta one of the strings because '.' is a meta (regex command) character.

If you use substr, you'll have problems if the length of the part you are trying to match can vary. Ie. Could the strings be '13.2.3' & '13.2' for example.

Using index will allow you to avoid both these problems. You simple want to know if the shorter string matches the longer string at position 0:

$var1 = '1.1.2'; $var2 = '1.1'; if( index( $var1, $var2 ) == 0 ) { print "matches" } else { print "Doesn't match" }

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."

Replies are listed 'Best First'.
Re^2: Regex question
by Skeeve (Parson) on May 22, 2007 at 12:44 UTC

    This will never match and is completly wrong as you mixed up $var1 and $var2.

    It should be

    index( $var2, $var1 ) == 0

    but this will still be wrong because

    $var2='1.11.2'; $var1='1.1';

    would give you a false match


    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
      This will never match and is completly wrong as you mixed up $var1 and $var2.

      Um, no.

      C:\parrot>p1 [0] Perl> $var1 = '1.1.2'; $var2 = '1.1'; if( index( $var1, $var2 ) == 0 ) { print "matches" } else { print "Doesn't match" };; matches [0] Perl> $var1 = '1.1.2'; $var2 = '1.1'; if( index( $var2, $var1 ) == 0 ) { print "matches" } else { print "Doesn't match" };; Doesn't match

      but this will still be wrong because

      $var2='1.11.2'; $var1='1.1';

      would give you a false match

      That's a good catch though. It's also easily fixed:

      [0] Perl> $var1 = '1.11.2'; $var2 = '1.1'; if( index( $var1, "$var2." ) == 0 ) { print "matches" } else { print "Doesn't match" };; Doesn't match

      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.

        Indeed! I mixed it up, not you.

        But your fix doesn't help with:

        $var2='1.1'; $var1='1.1';

        It will give you a false negative ;-) See my solution above which handle both cases.


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