2012-01-12 25 views

回答

7

這一個可以做TE工作:

/^(\w+\b).*\b\1$/ 

解釋:

/   : regex delimiter 
^  : start of string 
    (  : start capture group 1 
     \w+ : one or more word character 
     \b : word boundary 
    )  : end of group 1 
    .*  : any number of any char 
    \b  : word boundary 
    \1  : group 1 
    $   : end of string 
/   : regex delimiter 
+0

謝謝! '\ 1'是我搜索的。 – 2012-01-12 10:04:15

0

我不認爲正則表達式在這裏是正確的選擇。爲什麼該行不分成數組,並比較第一個和最後一個項目:

在C#:

string[] words = line.Split(' '); 
return words.Length >= 2 && words[0] == words[words.Length - 1]; 
+0

爲什麼您認爲RegExps在這裏不是正確的選擇? 在正則表達式中'\ b'實際上更好,因爲它不僅匹配whitespcaces。而在大字符串你的解決方案可能會更慢。 – kirilloid 2012-01-12 10:31:03

+0

@kirilloid:我認爲正則表達式帶有一個開銷,而這個解決方案並不需要。然而,其他答案中提供的正則表達式解決方案絕對更優雅。關於性能,「代碼」解決方案可以改進。 \ *趨於刪除我的答案\ *;) – Stefan 2012-01-12 10:37:54

5

M42的答案是,除了退化情況確定 - 它不會匹配字符串只有一個字。爲了接受這些一個正則表達式使用內:

/^(?:(\w+\b).*\b\1|\w+)$/ 

還可選配只在必要的部分可能是顯著快上非常大的字符串。我這裏還有我的解決方案上的javascript:

正則表達式:

function areEdgeWordsTheSame(str) { 
    var m = str.match(/^(\w+)\b/); 
    return (new RegExp(m[1]+'$')).test(str); 
} 

字符串:

function areEdgeWordsTheSame(str) { 
    var idx = str.indexOf(' '); 
    if (idx < 0) return true; 
    return str.substr(0, idx) == str.substr(-idx); 
}