【问题标题】:Fuzzy matching in PerlPerl 中的模糊匹配
【发布时间】:2019-11-12 03:02:37
【问题描述】:

我想对不同的字符串做一些模糊匹配,比如, air twist 应该与 air-twistair twistsair-twists 匹配。

在 perl 中,我们是否有一些模块可以做到这一点?还是我们可以手动执行,例如使用正则表达式?

【问题讨论】:

  • 查看 this post 获取有关模块和方法的独家新闻,以及链接
  • 我喜欢String::Similarity。 :) 它很容易使用。
  • 是的,很高兴有可供选择的选项:)。它们在最佳用途方面都略有不同。 this post中的另一个例子……我希望这些足够有用,所以不需要在这里写它们?
  • 已经有很好的教程了。 String::Approx 非常适合我正在考虑的另一个场景:在目标字符串的模糊匹配周围添加 HTML 标记。 :)

标签: perl fuzzy-comparison


【解决方案1】:

下面的代码可以完成这项工作

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

【讨论】:

    【解决方案2】:

    如果您只想匹配两个特定单词之间的任何非字母数字字符,您可以使用这样的正则表达式:

    /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
    

    【讨论】:

      猜你喜欢
      • 2018-04-26
      • 2011-01-18
      • 2015-04-26
      • 1970-01-01
      • 2016-02-11
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多