2013-02-28 33 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."); 

会找到两条第一条线,但不是第三条。