正则表达式-使用java-8在文件中查找模式
我从一个类似的问题中找到了以下解决方案。以下是链接: 这是赫尔伍德给出的解决方案。这对我很有用。但我不知道为什么它不打印任何东西 我试图匹配“是”这个词后面的任何内容 我的输入文件包含以下行:正则表达式-使用java-8在文件中查找模式,java,regex,java-8,Java,Regex,Java 8,我从一个类似的问题中找到了以下解决方案。以下是链接: 这是赫尔伍德给出的解决方案。这对我很有用。但我不知道为什么它不打印任何东西 我试图匹配“是”这个词后面的任何内容 我的输入文件包含以下行: my name is tom my dog is hom. 我需要打印 tom hom. 但是没有打印任何内容您无法获得所有结果,因为Stream#findFirst返回流中第一个满足的元素,请改用Stream#forEach 您应该删除根本不出现的符号,并将Matcher#matches替换为Ma
my name is tom
my dog is hom.
我需要打印
tom
hom.
但是没有打印任何内容您无法获得所有结果,因为
Stream#findFirst
返回流中第一个满足的元素,请改用Stream#forEach
您应该删除根本不出现的符号
,并将Matcher#matches
替换为Matcher#find
,因为Matcher#matches
将匹配整个输入。例如:
Pattern p = Pattern.compile("is (.+)");
stream1.map(p::matcher)
.filter(Matcher::find)
.forEach(matcher -> System.out.println(matcher.group(1)));
只需删除正则表达式中的单引号。我假设,既然你说你想匹配“是”之后的任何内容,如果“是”之后没有任何内容,你可能想打印空白;因此,在我使用的正则表达式中,用“.*”代替“+” 这应该行得通
Pattern p = Pattern.compile("is (.*)");
stream1.map(p::matcher)
.filter(Matcher::matches)
.filter(Matcher::find)
.forEach(matcher -> System.out.println(matcher.group(1)));
谢谢,但我还是没有得到任何东西
Pattern p = Pattern.compile("is (.*)");
stream1.map(p::matcher)
.filter(Matcher::matches)
.filter(Matcher::find)
.forEach(matcher -> System.out.println(matcher.group(1)));