regexperl

Match any substring from the beginning of a word


For example, with a line like previous, I want the pattern to match the lines p, pr, pre, prev, etc., all the way up to previous. I do NOT want it to match lines like prevalent or previse. Is there a pattern to accomplish this aside from the obvious (^(p|pr|pre|prev|...|previous)$)?

Note: I do not need to capture it like in the above pattern, and I'm using Perl's regular expression flavor (in Perl).


Solution

  • I don't think regex is the best (or most readable) way to do this:

    $str = "previous";
    $input = "prev";
    $length = length($input);
    
    $strcheck = substr($str, 0, $length);
    $incheck = substr($input, 0, $length);
    
    if ($strcheck =~ $incheck && $length != 0) {
        // do something with $input
    }