如果元素(ID、Z、X、Y)的顺序始终相同,则可以使用正则表达式:
保存值的类(为简洁起见,字段是公开的):
public class Something {
public int id;
public int z;
public int x;
public int y;
@Override
public String toString() {
return "ID=" + id + " x=" + x + " y=" + y + " z=" + z;
}
}
那么,带有正则表达式的方法可以有以下内容:
final String input ="ID=1923\nZ=19\nX=123\nY=102\r\nID=133\nZ=11\nX=14\nY=12r\nID=1313\nZ=121\nX=134\nY=19";
final String regex = ".*?ID=(\\d+).*?Z=(\\d+).*?X=(\\d+).*?Y=(\\d+)";
final Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
final Matcher matcher = pattern.matcher(input);
final List<Something> somethings = new ArrayList<>();
while (matcher.find()) {
final Something something = new Something();
something.id = Integer.parseInt(matcher.group(1));
something.z = Integer.parseInt(matcher.group(2));
something.x = Integer.parseInt(matcher.group(3));
something.y = Integer.parseInt(matcher.group(4));
somethings.add(something);
}
for (final Something something : somethings) {
System.out.println(something);
}
产生以下输出:
ID=1923 x=123 y=102 z=19
ID=133 x=14 y=12 z=11
ID=1313 x=134 y=19 z=121