2012-09-22 48 views

回答

3

你的正則表達式有幾個問題。例如,\b字邊界不能用於字符類,因此[^\b]*將無法​​按預期工作。

你可能要像

(?s)\b(\w+)\b.*\b\1\b 

這將從字到最後一個的第一次出現在整個文本相匹配。這可能不是你實際想要的。

另一個想法:

(?s)\b(\w+)\b.*?\b\1\b 

這隻會匹配從詞第一次出現在旁邊的文本。

用這兩種方法的問題是,例如在文本像

foo bar bar foo 

正則表達式將匹配來自foofoo,盲目地忽略了存在重複bar在兩者之間。

所以,如果你真的想找到發生在重複的所有單詞,然後用

(?s)\b(\w+)\b(?=.*?\b\1\b) 

說明:

(?s)  # Allow the dot to match newlines 
\b(\w+)\b # Match an entire word 
(?=  # Assert that the following regex can be matched from here: 
.*?  # Any number of characters 
\b\1\b # followed by the word that was previously captured 
)   # End of lookahead 
+0

感謝我只需要這個\ B(\ w +)\ b 。* \ b \ 1 \ b但是,謝謝 – kabell