虽然正则表达式可以做到这一点,但听起来您的问题也可以通过index
功能:
say index($haystack, $needle) >= 0 ? 'match' : 'fail'; # any position
say index($haystack, $needle) == 0 ? 'match' : 'fail'; # anchored at start
The index
函数区分大小写。如果您想要不敏感的匹配,请应用uc
or lc
两个参数的函数。
虽然index
函数将比正则表达式快得多,如果您确实需要正则表达式解决方案,您可以构建一个正则表达式生成器,它生成一系列将执行部分匹配的交替。
sub build_partial {
my ($str, $min) = (@_, 1);
my @re;
for (0 .. length($str) - $min) {
my $str = substr $str, $_;
for ($min .. length $str) {
push @re, quotemeta substr $str, 0, $_
}
}
my $re = join '|' => sort {length $a <=> length $b} @re;
qr/^(?:$re)$/i
}
my $haystack = 'MCF-7';
my $needle = 'MCF';
my $regex = build_partial $haystack;
say $needle =~ /$regex/ ? 'match' : 'fail'; # match
生成的正则表达式为MCF-7
看起来像这样:
/^(?:M|C|F|7|MC|CF|\-|MCF|F\-|\-7|CF\-|F\-7|MCF\-|CF\-7|MCF\-7)$/i
即使针是大海捞针中的单个字符,它也会匹配。build_partial
采用一个可选数字,指示匹配所需的最小长度:
my $regex_3 = build_partial $haystack, 3;
它产生这个正则表达式:
/^(?:MCF|CF\-|F\-7|MCF\-|CF\-7|MCF\-7)$/i
这些模式匹配从任意位置开始的子字符串。如果你想把它固定在绳子的前面,build_partial
变得更简单一点:
sub build_partial {
my ($str, $min) = (@_, 1);
my $re = join '|' => map {
quotemeta substr $str, 0, $_
} $min .. length $str;
qr/^(?:$re)$/i
}