Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find pattern in files with java 8

Tags:

java

regex

java-8

consider I have a file like (just an excerpt)

name: 'foobar'

I like to retrieve foobar when I discover the line with name.

My current approach is

Pattern m = Pattern.compile("name: '(.+)'");
try (Stream<String> lines = Files.lines(ruleFile)) {
    Optional<String> message = lines.filter(m.asPredicate()).findFirst();
    if (message.isPresent()) {
        Matcher matcher = m.matcher(message.get());
        matcher.find();
        String group = matcher.group(1);
        System.out.println(group);
    }
}

which looks not nice. The excessive use of the pattern and matcher seems wrong.

Is there a easier/better way ? Especially if I have multiple keys I like to search like this ?

like image 358
Emerson Cod Avatar asked Jan 14 '16 13:01

Emerson Cod


People also ask

How do I extract a pattern in Java?

Solution: Use the Java Pattern and Matcher classes, supply a regular expression (regex) to the Pattern class, use the find method of the Matcher class to see if there is a match, then use the group method to extract the actual group of characters from the String that matches your regular expression.

Is there pattern matching in Java?

Pattern matching has modified two syntactic elements of the Java language: the instanceof keyword and switch statements. They were both extended with a special kind of patterns called type patterns. There is more to come in the near future.

How do you find a string pattern?

To check if a String matches a Pattern one should perform the following steps: Compile a String regular expression to a Pattern, using compile(String regex) API method of Pattern. Use matcher(CharSequence input) API method of Pattern to create a Matcher that will match the given String input against this pattern.


1 Answers

I would expect something more like this, to avoid matching the pattern twice:

Pattern p = Pattern.compile("name: '([^']*)'");
lines.map(p::matcher)
     .filter(Matcher::matches)
     .findFirst()
     .ifPresent(matcher -> System.out.println(matcher.group(1)));

That is, for each string's matcher, get the first one that matches, for that one print out the first group.

like image 83
khelwood Avatar answered Sep 22 '22 03:09

khelwood