【发布时间】:2019-11-12 03:02:37
【问题描述】:
我想对不同的字符串做一些模糊匹配,比如,
air twist 应该与 air-twist 或 air twists 或 air-twists 匹配。
在 perl 中,我们是否有一些模块可以做到这一点?还是我们可以手动执行,例如使用正则表达式?
【问题讨论】:
标签: perl fuzzy-comparison
我想对不同的字符串做一些模糊匹配,比如,
air twist 应该与 air-twist 或 air twists 或 air-twists 匹配。
在 perl 中,我们是否有一些模块可以做到这一点?还是我们可以手动执行,例如使用正则表达式?
【问题讨论】:
标签: perl fuzzy-comparison
下面的代码可以完成这项工作
use strict;
use warnings;
my $regex = qr/air.twists{0,1}/;
while( <DATA> ) {
print if /$regex/;
}
__DATA__
air-twist
air balloon
air twists
fried potato
air-twist
Cesar salad
air-propeller
air show
broken car
new bicycle
【讨论】:
如果您只想匹配两个特定单词之间的任何非字母数字字符,您可以使用这样的正则表达式:
/air[^a-z0-9]twists/i
[^a-z0-9] 匹配任何非字母或数字的字符;因此它将匹配空格或标点符号等内容。尾随 i 后缀告诉正则表达式忽略字母大小写。
这个特定的正则表达式将匹配如下字符串:
air twists
AIR TWISTS
Air-Twists
AIR_TWISTS
air/twists
air.twists
air:twists
...等等。
如果要匹配多个分隔单词的非字母数字字符,请在正则表达式中添加 +:
/air[^a-z0-9]+twists/i
这匹配更多的字符串,比如:
air twists
air---twists
air, twists
air && twists
air<=>twists
【讨论】: