正则表达式,仅过滤数字

时间:2017-12-01 08:33:33

标签: java regex graph

我是Java的初学者,所以目前我正在学习正则表达式,我想只过滤文件txt中的数字。我需要在图形中添加边缘,但首先我要过滤我的数字。

档案.txt

1 2
1;3 5 4 3        4 
1       
7
4@2
5   6 1
6.8
9 10m

我的代码:

public class Main {

    private static final String filename = "/Users/user/Desktop/exercises/files/test.txt";

    public static void main(String[] args) {

        try(BufferedReader br = new BufferedReader(new FileReader(filename))) {

            String line = br.readLine();

            while(line!= null) {
                String[] edge = line.trim().split("\\s+");

                for(int i = 0; i < edge.length; i+=2) {
                    int v = Integer.parseInt(edge[i]);
                    int u = Integer.parseInt(edge[i] + 1);
                    System.out.println(v + ", " + u);
                }
                line = br.readLine();
            }


        }catch(IOException e) {
            System.out.println("File does not exist!!");
        }

    }

}

例外:

1, 11
Exception in thread "main" java.lang.NumberFormatException: For input string: "1;3"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at javaproject1.Main.main(Main.java:22)

1 个答案:

答案 0 :(得分:0)

您的正则表达式仅在空白处拆分,因此1; 3不会拆分。 '[\ s;] +'可能会让您超越分号。如果您真的想除数字以外的任何东西,请使用[[^ \ d] +',…– zzxyz