I have found the following solution from a similar question. Here is the link:
Find pattern in files with java 8
Pattern p = Pattern.compile("is '(.+)'");
stream1.map(p::matcher)
.filter(Matcher::matches)
.findFirst()
.ifPresent(matcher -> System.out.println(matcher.group(1)));
This is the solution given by khelwood. This is very useful to me. But I don't know why it is not printing anything.
I am trying to match anything that follows the word 'is '.
And my input file contains these lines:
my name is tom
my dog is hom.
I need to print
tom
hom.
But nothing is printed
you can't get all of the result since Stream#findFirst is return the first satisfied element in a stream, please using Stream#forEach instead.
you should remove the symbol ' that doesn't appear there at all, and replace Matcher#matches with Matcher#find, because Matcher#matches will matches the whole input. for example:
Pattern p = Pattern.compile("is (.+)");
stream1.map(p::matcher)
.filter(Matcher::find)
.forEach(matcher -> System.out.println(matcher.group(1)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With