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
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);
}
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());
}
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
...
}
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]
"\\((\\d*),(\\d*)\\)\\s*\\((\\d*),(\\d*)\\)"
This will work:
String[] values = s.substring(1).split("\\D+");