perl中的正则表达式匹配

时间:2014-02-12 05:16:35

标签: regex perl

我想使用最小可能代码(字符数)来检查两个相同长度的单词是否仅相差一个字符。我有一个逻辑,我用一个for循环来逐步浏览单词中的每一个字符并检查整个集合中是否只有一个字符不同......但这似乎是一段很长的代码... < / p>

有人可以建议一些可以用来以更紧凑的方式做到的正则表达式吗?

1 个答案:

答案 0 :(得分:2)

您可以连接这两个单词并使用此模式:

"bilboquetbilbaquet" =~ /^(.*)(.)(.*)\1(?!\2).\3$/   # exactly one character different

"bilboquetbilbaquet" =~ /^(.*)(.)(.*)\1.\3$/  # one character max 

模式细节:

^         # anchor for the start of the string
(.*)      # capture group 1: zero or more characters
(.)       # capture group 2: one character
(.*)      # capture group 3: zero or more characters
\1        # backreference to group 1
(?!\2)    # negative lookahead: not followed by group 2 content
.         # one character
\3        # backreference to group 3
$         # anchor for the end of the string

示例:

my $strA = "bilboquet";
my $strB = "bilbaquet";

my $result = ($strA.$strB) =~ /^(.*)(.)(.*)\1(?!\2).\3$/;

print $result;