2013-02-28 34 views
-2

(字邊界)我都存儲在一個字符串文本文件名爲Str看起來像這樣的內容:如何找到一組詞的使用正則表達式

Str = "Cat is an animal\n" + 
     "Cat is small\n" + 
     "Cat is a pet\n"; 

我寫這個代碼搜索的字Cat

Pattern pattern = Pattern.compile("(\\bCat\\b)"); 
Matcher match = pattern.matcher(Str); 

while (match.find()) { 
    String tempStr = "I found " + match.group() + "\n"; 
} 

上面產生這樣的輸出:

I found Cat 
I found Cat 
I found Cat 

這是我的問題。如何使用關鍵字Cat查找整個句子,以便輸出結果爲:

I found Cat is an animal 
I found Cat is small 
I found Cat is a pet 

這是什麼正則表達式?

+0

你有什麼試過?你沒有顯示任何找到該句子的企圖/線索。我也會說這個問題缺乏細節/背景。 – 2013-02-28 20:19:21

+0

是的,我找到了解決我的問題的方案。我嘗試了簡單的正則表達式Vlad L建議並返回符合我預期的輸出。謝謝! – 2013-02-28 20:58:39

回答

0

你並不真正需要的單詞邊界在這裏,你可以把它簡單:

"(Cat.*?)/n" 

,然後得到match.group(1)

+0

這一款適合我。感謝大家在這裏的幫助:)。 – 2013-02-28 20:57:07

0

假設由「句子」(這是可以用不同的方式來定義非常寬泛的術語)表示,直到下一個週期(.),你可以用

Pattern pattern = Pattern.compile("(\\bCat\\b.*\\.)"); 

.* 0以上的任何嘗試性格

\\.句號

+0

我在我的問題中犯了一個錯誤。每句話都不以句號結束。 – 2013-02-28 20:13:07

+0

所以現在我明白每個句子都以換行符('\ n')結尾,這是正確的嗎?你應該在你的問題中具體澄清這一點。 – m0skit0 2013-02-28 20:18:37

0

結果你想使用這個詞的邊界,以避免像Catwoman匹配詞?如果是這樣,你幾乎已經在那裏。

Pattern pattern = Pattern.compile(".*\\bCat\\b[^.]*\\."); 
Matcher match = pattern.matcher("a super Cat too cute to be true.\n" + 
           "and an other Cat.\n" + 
           "but not thatCat nor Catwoman no no no."); 

會找到兩條第一條線,但不是第三條。