使用java 8在文件中查找模式 [英] Find pattern in files with java 8

查看:261
本文介绍了使用java 8在文件中查找模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑我有一个类似的文件(只是一个摘录)

consider I have a file like (just an excerpt)

name: 'foobar'

当我发现<$ c $行时,我想检索 foobar c> name 。

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

我目前的做法是

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 ?

推荐答案

我希望更像这样的东西,以避免匹配模式两次:

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.

这篇关于使用java 8在文件中查找模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆