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 ?
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.
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.
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.
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.
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