Regular Expression Matching -Java

匿名 (未验证) 提交于 2019-12-03 02:34:02

问题:

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 can I do it with regular expression matching in java. Thankx.

回答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] 


回答2:

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


回答3:

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


回答4:

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


回答5:

This will work:

String[] values = s.substring(1).split("\\D+"); 


回答6:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!