2014-02-12 168 views
0

我想使用最小可能的代碼(字符數)來檢查兩個相同長度的單詞是否相差一個字符。我有一個邏輯,我使用for循環遍歷單詞中的每個單詞,並檢查整個集合是否只有一個字符不同......但這似乎是一段長長的代碼...perl中的正則表達式匹配

有人可以建議一些正則表達式,可以用它來以更緊湊的方式嗎?

+4

這個問題似乎是題外話,因爲它是關於代碼高爾夫的。這可能是http://codegolf.stackexchange.com上的主題 – devnull

回答

2

可以Concat的兩個詞,並使用此模式:

"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; 
+0

感謝您給予最大的一個字符表達式......但是,您能解釋一下您在做什麼嗎?我有正則表達式的基本想法,但我無法理解表達式... – RoyOneMillion

+0

這個正則表達式:/^(.*)(.)(.*)\1.\3$/ fits「bilboquetbilbaquet」like這個: /^(bilb)o(quet)(bilb)a(quet)$ / –