Regular Expression Matching -Java

后端 未结 6 1657
轻奢々
轻奢々 2021-01-23 20:48

I am taking input from a file in following format:

(int1,int2) (int3,int4)

Now I want to read int1, int2, int3 and int4 in my Java code. How ca

相关标签:
6条回答
  • 2021-01-23 20:50
    Pattern p = Pattern.compile("\\((\\d+),(\\d+)\\)\\s+\\((\\d+),(\\d+)\\)");
    String input = "(123,456) (789,012)";
    
    Matcher m = p.matcher(input);
    
    if (m.matches()) {
      int a = Integer.parseInt(m.group(1), 10);
      int b = Integer.parseInt(m.group(2), 10);
      int c = Integer.parseInt(m.group(3), 10);
      int d = Integer.parseInt(m.group(4), 10);
    }
    
    0 讨论(0)
  • 2021-01-23 20:54

    To build on your own method, you can use a much simpler regex:

    String s = "(1,2) (3,4)";
    Pattern p = Pattern.compile("\\d+");
    Matcher m = p.matcher(s);
    while (m.find()) {
        System.out.println(m.group());
    }
    
    0 讨论(0)
  • 2021-01-23 20:58

    You could do something like:

    String str = "(1,2) (3,4)";
    Matcher m = Pattern.compile("\\((\\d+),(\\d+)\\) \\((\\d+),(\\d+)\\)").matcher(str);
    if (m.matches()) {
       System.out.println(m.group(1)); // number 1
       ...
    }
    
    0 讨论(0)
  • 2021-01-23 20:59
    String[] ints = "(2,3) (4,5)".split("\\D+");
    System.out.println(Arrays.asList(ints));
    // prints [, 2, 3, 4, 5]
    

    To avoid empty values:

    String[] ints = "(2,3) (4,5)".replaceAll("^\\D*(.*)\\D*$", "$1").split("\\D+");
    System.out.println(Arrays.asList(ints));
    // prints [2, 3, 4, 5]
    
    0 讨论(0)
  • 2021-01-23 21:07

    "\\((\\d*),(\\d*)\\)\\s*\\((\\d*),(\\d*)\\)"

    0 讨论(0)
  • 2021-01-23 21:13

    This will work:

    String[] values = s.substring(1).split("\\D+");
    
    0 讨论(0)
提交回复
热议问题