简体   繁体   English

正则表达式从字符串中提取浮点数

[英]Regex to extract float from String

I have a file which contains the following string data 我有一个包含以下字符串数据的文件

...
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
....

From this file I want to extract all the numbers from the lines starting with 'v' and 'f'. 从这个文件中,我想从以“ v”和“ f”开头的行中提取所有数字。 I have written the following regex for it. 我为此编写了以下正则表达式。

v(?:\s([0-9\-\.]+))+

Output:
group 1: -0.100000

f(?:\s([0-9]+))+

Output:
group 1: 22

But as you can see the output is only extracting the last numbers from each line, I want the output as follows: 但是如您所见,输出仅从每行提取最后一个数字,我希望输出如下:

Output:
group 1: -0.570000
group 2: -0.950000
group 3: -0.100000

Output:
group 1: 34
group 2: 22

Can someone please help me here? 有人可以在这里帮我吗?

Here is the solution which I used finally, in case someone needs it. 如果有人需要,这是我最后使用的解决方案。

I used two Regex instead of using string splitting as suggested in the above comments. 我使用了两个正则表达式,而不是按照上面的注释中的建议使用字符串拆分。

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM