Java中的等效findAll python方法
我想知道Java中是否有与之等价的python方法findAll。我经常逐行读取文件,检查该行是否与正则表达式匹配。因此,如果使用python,我可以:Java中的等效findAll python方法,java,python,methods,findall,equivalent,Java,Python,Methods,Findall,Equivalent,我想知道Java中是否有与之等价的python方法findAll。我经常逐行读取文件,检查该行是否与正则表达式匹配。因此,如果使用python,我可以: # Feed the file text into findall(); it returns a list of all the found strings strings = re.findall(r'some pattern', f.read()) 在Java中有类似的方法吗?您可以使用java8流api List<Str
# Feed the file text into findall(); it returns a list of all the found strings
strings = re.findall(r'some pattern', f.read())
在Java中有类似的方法吗?您可以使用java8流api
List<String> strings = null;
try(Stream<String> lines = Files.lines(Paths.get("/path/to/file"))) {
strings = lines
.filter(line -> line.matches("some pattern"))
.collect(Collectors.toList());
}
列表字符串=null;
try(streamlines=Files.lines(path.get(“/path/to/file”))){
字符串=行
.filter(line->line.matches(“某些模式”))
.collect(Collectors.toList());
}
如果不需要try块,可以使用(这将读取内存中的所有文件行)
List strings=文件
.readAllLines(path.get(“/path/to/file”))
.stream()
.filter(line->line.matches(“某些模式”))
.collect(Collectors.toList());
您可以使用java8流api
List<String> strings = null;
try(Stream<String> lines = Files.lines(Paths.get("/path/to/file"))) {
strings = lines
.filter(line -> line.matches("some pattern"))
.collect(Collectors.toList());
}
列表字符串=null;
try(streamlines=Files.lines(path.get(“/path/to/file”))){
字符串=行
.filter(line->line.matches(“某些模式”))
.collect(Collectors.toList());
}
如果不需要try块,可以使用(这将读取内存中的所有文件行)
List strings=文件
.readAllLines(path.get(“/path/to/file”))
.stream()
.filter(line->line.matches(“某些模式”))
.collect(Collectors.toList());
好吧,Java中没有这样的方法。但您可以使用如下类似的代码
java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("regex pattern");
try(BufferedReader reader = new BufferedReader(new FileReader(new File("file path")))) {
reader.lines().forEach(line -> {
java.util.regex.Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
String gr = matcher.group(1); // Depends on the regex provided. Better if it could be grouped.
}
});
}
嗯,Java中没有这样的方法。但您可以使用如下类似的代码
java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("regex pattern");
try(BufferedReader reader = new BufferedReader(new FileReader(new File("file path")))) {
reader.lines().forEach(line -> {
java.util.regex.Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
String gr = matcher.group(1); // Depends on the regex provided. Better if it could be grouped.
}
});
}
嗯,你可以使用一个流,一个过滤器和一个收集器。Python来自于与Java不同的“文化”,具有更多的“内置”文本处理功能,但在Java中使用较小的构建块很容易实现这一任务。Python来自与Java不同的“文化”,具有更多的“内置”文本处理功能,但在Java中使用较小的构建块很容易完成此任务。应注意匹配整行的
matches
方法,因此,可能需要将模式从some pattern
更改为*some pattern.*
。应注意匹配整行的matches
方法,因此可能需要将模式从some pattern
更改为*some pattern.
。