Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex - Find pattern in file with java-8

Tags:

java

regex

java-8

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

like image 432
Ilak Avatar asked Feb 15 '26 04:02

Ilak


1 Answers

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)));
like image 125
holi-java Avatar answered Feb 16 '26 17:02

holi-java



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!