3

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

2 Answers 2

3

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)));
Sign up to request clarification or add additional context in comments.

Comments

1

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)));

1 Comment

Thanks, but I am not getting anything still

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.