【问题标题】:Parse a string in a particular format解析特定格式的字符串
【发布时间】:2016-04-29 20:15:54
【问题描述】:

我有一个如下所示的响应字符串,我需要对其进行解析并将其存储在我的类中。格式如下:

  • 任务名称后跟此虚线------------- 也是固定的
  • 然后在key:value 对下方。它可以有很多键值对

下面是响应字符串。

abc-------------
Load:79008
Peak:4932152

def-------------
Load:79008
Peak:4932216

ghi-------------
Load:79008
Peak:4874588

pqr-------------
Load:79008
Peak:4874748

下面是我的课:

public class NameMetrics {

    private String name;
    private Map<String, String> metrics;

    // setters and getters

}

在上面的类中,name 应该是 abcmetrics 映射应该有 Load 作为键和 79008 作为值,与其他键:值对相同。我正在考虑使用正则表达式,但不确定我是否可以在这里使用正则表达式。

private static final Pattern PATTERN = Pattern.compile("(\\S+):\\s*(\\S*)(?:\\b(?!:)|$)");

String response = restTemplate.getForObject(url, String.class);
// here response will have above string.

最好的方法是什么?

【问题讨论】:

  • 不需要正则表达式,只需逐行迭代输入
  • 读行。跳过空白行。如果line.indexOf(':') 返回-1,你有一个“标题”行,否则你有一个键:值对,所以substring() 键和值。冲洗并重复。

标签: java regex string parsing


【解决方案1】:
BufferedReader reader = new BufferedReader(...???...);
NameMetrics current = null;
List<NameMetrics> result = new ArrayList<>();
while (true) {
  String s = reader.readLine();
  if (s == null) {
    break;  // end reached
  }
  if (s.trim().isEmpty()) {
    continue;  // Skip empty line
  }
  int cut = s.indexOf(':');
  if (cut == -1) {
    cut = s.indexOf('-');
    if (cut == -1) {
      continue;
    }
    current = new NameMetrics();
    current.setName(s.substring(0, cut));
    result.add(current);
  } else if (current != null) {
    current.setMetrics(s.substring(0, cut), s.substring(cut+1));
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    相关资源
    最近更新 更多