你好,
我有一个尝试查找短语的应用程序。我假设短语以大写字母开头,以点结尾,中间可以包含任何内容。
下面是我的代码:
for(String s: manyLines)
{
Pattern pa = Pattern.compile("([A-Z]{1})(.*)(\\.)");
Matcher ma = pa.matcher(s);
if(ma.find())
{
manyPhrase.add(s);
}
但是正则表达式似乎不起作用,因为 manyPhrase (ArryList of Strings) 它获取所有行而不仅仅是短语。
例如,我的输入文件有:
Fox fox runs to escape dog dog. ak; Rabbit rabbit runs to escape fox fox. 123.5, Carrot waits for rabbit rabbit in the field to return. more than expected
它应该返回
Fox fox runs to escape dog dog. Rabbit rabbit runs to escape fox fox. Carrot waits for rabbit rabbit in the field to return.
此致
最佳答案
.*
是贪心的,匹配所有内容直到最后一个周期。
尝试使用非贪婪匹配器
[A-Z].*?\\.
或者,更好的是,使用更精确的“大写字母、非句号、句号”正则表达式:
[A-Z][^.]*\\.
最后,如果你使用 ()
进行分组,最好使用 (?:)
作为非捕获组,除非你真的想存储结果子表达式
关于尝试使用 Regex 查找短语并显示找到的短语的 Java 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23724703/