【发布时间】:2019-06-24 20:07:08
【问题描述】:
我正在做一个项目,我需要扫描一个文件夹并扫描每个文件中的特定单词(比如“@MyPattern”)。
我期待有一种最佳方法来设计这样的场景。 首先,我的工作如下:
//Read File
List<String> lines = new ArrayList<>();
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach(line-> lines.add(line));
} catch (IOException e) {
e.printStackTrace();
}
//Create a pattern to find for
Predicate<String> patternFilter = Pattern
.compile("@MyPattern^(.+)")
.asPredicate();
//Apply predicate filter
List<String> desiredWordsMatchingPattern = lines
.stream()
.filter(patternFilter)
.collect(Collectors.<String>toList());
//Perform desired operation
desiredWordsMatchingPattern.forEach(System.out::println);
我不确定为什么这不起作用,即使文件中有多个匹配“@MyPattern”的单词。
【问题讨论】:
-
建议:只需仔细检查您的正则表达式一次。
-
看起来你的正则表达式有问题。
-
我的字符串是这样的:“@Traces("10869") @Details('用户正在查看用户配置文件') 给出:用户对用户配置文件开放“我期待提取” 10869" 在@Traces 之后。 so 的正则表达式应该是什么
-
像
@MyPattern这样的正则表达式将匹配@MyPattern而没有别的,即它不会匹配@Traces(为什么要匹配?)。除此之外,您的谓词将选择包含匹配项的行,但不会提取匹配项。您可以为此使用Scanner。 -
当我问您是否会接受其中一个(非常不同的)答案时,我希望我不会让您陷入任何忠诚度冲突?未来的读者会发现知道哪个对您更有帮助很有帮助。见What should I do when someone answers my question?
标签: java string text java-8 string-matching