解析特定格式的字符串 [英] Parse a string in a particular format
本文介绍了解析特定格式的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的响应字符串,我需要解析它并将其存储在我的类中.格式如下:
I have a response String as shown below which I need to parse it and store it my class. Format is shown below:
- 任务名称后跟这条虚线
-------------
也是固定的 - 然后就在
key:value
对下方.它可以有多个键值对
- task name followed by this dotted line
-------------
which is also fixed - and then just below
key:value
pair. It can have many key value pair
下面是响应字符串.
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
应该是 abc
并且 metrics
地图应该有 Load
作为键和79008
作为值,与其他键值对相同.我想使用正则表达式,但不确定是否可以在这里使用正则表达式.
In the above class, name
should be abc
and metrics
map should have Load
as the key and 79008
as the value and same with other key:value pairs. I was thinking to use regex but not sure whether I can use regex here.
private static final Pattern PATTERN = Pattern.compile("(\\S+):\\s*(\\S*)(?:\\b(?!:)|$)");
String response = restTemplate.getForObject(url, String.class);
// here response will have above string.
最好的方法是什么?
推荐答案
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));
}
}
这篇关于解析特定格式的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文