例如,对于 previous
之类的行,我希望模式与 p
、 pr
、 pre
、 prev
等行匹配,一直到 previous
。我不希望它匹配 prevalent
或 previse
之类的行。
除了明显的( ^(p|pr|pre|prev|...|previous)$
)之外,是否还有其他模式可以实现这一点?
注意:我不需要像上面的模式那样捕获它,并且
我正在使用 Perl 的正则表达式风格(在 Perl 中)。
最佳答案
我不认为正则表达式是最好的(或最易读的)方式来做到这一点:
$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
}
关于regex - 匹配单词开头的任何子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6747309/