开发者

Match any substring from the beginning of a word

开发者 https://www.devze.com 2023-03-21 15:05 出处:网络
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 pre

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).


/^p(r(e(v(i(o(u(s)?)?)?)?)?)?)?$/

And just to double check that it works:

for (qw/p pr pre previous prevalent previse/) {
    $result = (/^p(r(e(v(i(o(u(s)?)?)?)?)?)?)?$/? "yes" : "no");
    print "Checking $_: $result\n";
}

Produces:

Checking p: yes
Checking pr: yes
Checking pre: yes
Checking previous: yes
Checking prevalent: no
Checking previse: no


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
}


#!/usr/bin/perl
use strict;
use warnings;

my $string = "previous"; 
my @array = split //,$string;

chomp(my $input=<STDIN>); #take the input from the user
my @array2 = split //,$input;

my $i=0;

foreach (@array2){
        if($_ eq $array[$i]){
            print "$_ matched\n";
        }
$i++;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消