我有一个包含以下字符串数据的文件
...
v -0.570000 -0.950000 -0.100000
v 0.570000 -0.950000 -0.100000
v -0.570000 -0.760000 -0.100000
v 0.570000 -0.760000 -0.100000
...
f 34 22
f 3 35 3
f 345 22
f 55 632 76
f 55 632
....
我希望从这个文件中提取以' v'开头的行中的所有数字。并且' f'。我已经写了以下正则表达式。
v(?:\s([0-9\-\.]+))+
Output:
group 1: -0.100000
f(?:\s([0-9]+))+
Output:
group 1: 22
但是你可以看到输出只是从每一行中提取最后一个数字,我想要输出如下:
Output:
group 1: -0.570000
group 2: -0.950000
group 3: -0.100000
Output:
group 1: 34
group 2: 22
有人可以帮我吗?
答案 0 :(得分:0)
这是我最终使用的解决方案,以防有人需要它。
我使用了两个Regex而不是像上面评论中所建议的那样使用字符串拆分。
public class ObjParser {
private static final Pattern vertexLinePattern = Pattern.compile("^v\\s(.+)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private static final Pattern faceLinePattern = Pattern.compile("^f\\s(.+)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private static final Pattern vertexValuePattern = Pattern.compile("([0-9\\-\\.]+)");
private static final Pattern faceValuePattern = Pattern.compile("([0-9]+)");
private List<Float> vertices = new LinkedList<Float>();
private List<Short> faces = new LinkedList<Short>();
public void parseVertices(String data) {
Matcher matcher1 = vertexLinePattern.matcher(data);
while(matcher1.find()) {
String line = matcher1.group(1);
Matcher matcher2 = vertexValuePattern.matcher(line);
while(matcher2.find()) {
vertices.add(Float.parseFloat(matcher2.group(1)));
}
}
}
public void parseFaces(String data) {
Matcher matcher1 = faceLinePattern.matcher(data);
while(matcher1.find()) {
String line = matcher1.group(1);
Matcher matcher2 = faceValuePattern.matcher(line);
while(matcher2.find()) {
short no = (short)(Integer.parseInt(matcher2.group(1)) - 1); // -1 due to 1 based index in OBJ files
faces.add(no);
}
}
}
public List<Float> getVertices() {
return vertices;
}
public List<Short> getFaces() {
return faces;
}
}