我需要从文件中提取一些数据,以便将其转换为对象才能进行处理.
我收到以下格式的文本文件中的数据:
Card 1: 32 45 ... 88 1
我的模型是:
public class Card {
private Integer id;
private List<Integer> values;
// getters and setters
}
因此,在这个例子中,对象将是(JSON):
{
"id": 1,
"values": [32, 45, ..., 88, 1]
}
Note: In the model the numbers are formatted ad 100, so between 101 and 102 there are 2 spaces
我的目标是使用Pattern
和Matcher
提取所有数据,以获得比使用String#split()
更干净的解决方案.
在判断了一些像this one这样的帖子和从那里链接的帖子之后,我得出的结论是,我可以用以下内容提取id
字段
Matcher m = Pattern.compile("Card\\s+(\\d+):(\\s+(\\d+))+").matcher(input);
Integer id = Integer.parseInt(m.group(1));
但我不知道如何从输入中提取values
列表.是否可以使用此方法从该输入中提取值?它应该是这样的
Matcher m = Pattern.compile("Card\\s+(\\d+):(\\s+(\\d+))+").matcher(input);
Integer id = Integer.parseInt(m.group(1));
List<Integer> values = new ArrayList<>();
while (m.find()) {
values.add(m.group()); // or some other iteration to get groups from 2 to N
}
让我知道如果有其他信息或澄清需要.提前感谢您的回答.