Reputation: 158
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
Upvotes: 3
Views: 1736
Reputation: 1162
Just remove the single quotes in the regex. I am assuming since you said you want to match anything after 'is', you may want to print a blank if nothing follows 'is'; thus, the '.*' instead of '.+' in the regex I used.
This should work.
Pattern p = Pattern.compile("is (.*)");
stream1.map(p::matcher)
.filter(Matcher::matches)
.filter(Matcher::find)
.forEach(matcher -> System.out.println(matcher.group(1)));
Upvotes: 1
Reputation: 30686
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)));
Upvotes: 3