【发布时间】:2020-10-27 08:36:07
【问题描述】:
我有一个很长的文本,我正在提取一些特定的值,然后是一些特定的单词。这是我的长文本示例:
.........
FPS(FramesPerSecond)[ValMin: 29.0000, ValMax: 35.000]
.........
TotalFrames[ValMin: 100000, ValMax:200000]
.........
MemoryUsage(In MB)[ValMin:190000MB, ValMax:360000MB]
.........
这是我的代码:
File file = filePath.toFile();
JSONObject jsonObject = new JSONObject();
String FPSMin="";
String FPSMax="";
String TotalFramesMin="";
String TotalFramesMax="";
String MemUsageMin="";
String MemUsageMax="";
String log = "my//log//file";
final Matcher matcher = Pattern.compile("FPS/\(FramesPerSecond/\)/\[ValMin:");
if(matcher.find()){
FPSMin= matcher.end().trim();
}
但我不能让它工作。我哪里错了?基本上,我需要为每个字符串选择来自该长文本的相应值(最大值和最小值)并将它们存储到变量中。喜欢
FPSMin = 29.0000
FPSMax = 35.0000
FramesMin = 100000
Etc
谢谢
编辑: 我尝试了以下代码(在测试用例中)以查看解决方案是否可行,但我遇到了问题,因为除了对象之外我无法打印任何东西。代码如下:
@Test
public void whenReadLargeFileJava7_thenCorrect()
throws IOException, URISyntaxException {
Scanner txtScan = new Scanner("path//to//file//test.txt");
String[] FPSMin= new String[0];
String FPSMax= "";
//Read File Line By Line
while (txtScan.hasNextLine()) {
// Print the content on the console
String str = txtScan.nextLine();
Pattern FPSMin= Pattern.compile("^FPS\\(FramesPerSecond\\)\\[ValMin:");
Matcher matcher = FPSMin.matcher(str);
if(matcher.find()){
String MinMaxFPS= str.substring(matcher.end(), str.length()-1);
String[] splitted = MinMaxFPS.split(",");
FPSMin= splitted[0].split(": ");
FPSMax = splitted[1];
}
System.out.println(FPSMin);
System.out.println(FPSMax);
}
【问题讨论】:
-
不确定您想要实现什么,但您的代码甚至无法编译。我经常想知道为什么人们在使用正则表达式而不是首先尝试使用简单的方法(子字符串)。
-
我需要从文本日志中选择值并使用正则表达式将它们存储到变量中。例如,FPS 最小值、FPS 最大值等
-
@Smutje 如何使用子字符串做到这一点?这是一个日志文件,但很长
-
我建议通过删除所有不必要的代码行(例如文件部分)来简化您的示例,以缩小正则表达式不起作用的原因。此外,如果其他人可以在他们的机器上编译您的代码而无需额外开销,这也有助于其他人为您提供帮助。
标签: java regex extract matcher