我有一条命令的输出,该命令基本上在其中列出了一堆键/值对。输出没有明显的格式,因此我认为正则表达式将是最好的方法。

输出:http://pastebin.com/Hfu4nP3M

基本上,我需要存储第21-30行的键/值对(逗号分隔)并将它们存储在地图中。

是否可以使用正则表达式来做到这一点?

谢谢。

最佳答案

我不确定这是否是您想要的,但是由于您说过需要存储第21-30行的键/值对(逗号分隔),因此

 {memory,
     [{total,38751504},
      {processes,13711212},
      {processes_used,13711198},
      {system,25040292},
      {atom,662409},
      {atom_used,653371},
      {binary,287088},
      {code,18209655},
      {ets,1358504}]},


我假设您要读取memory之后存储在[...]中的值。

为此,您可以使用类似

//creating reader to get data from file
BufferedReader in = new BufferedReader(new InputStreamReader(
        new FileInputStream("data.txt")));// file with your data

StringBuilder sb = new StringBuilder();
String line = null;
while ((line = in.readLine()) != null) {
    sb.append(line.trim());// also remove unnecessary tabulators and
                            // spaces
}
in.close();

String data = sb.toString();

Pattern pattern = Pattern.compile("\\{memory,\\[(.*?)\\]");
Matcher m = pattern.matcher(data);
if (m.find()) {
    Pattern keyValuePattern = Pattern.compile("\\{(\\w*?),(\\d*?)\\}");
    Matcher matcher = keyValuePattern.matcher(m.group(1));
    while (matcher.find())
        System.out.println(matcher.group(1) + "->" + matcher.group(2));
} else
    System.out.println("not found");


输出量

total->38751504
processes->13711212
...

关于java - 正则表达式以捕获键/值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11865391/

10-14 10:37
查看更多