[英]Regular Expression Matching -Java
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. 现在,我想在我的Java代码中读取int1,int2,int3和int4。 How can I do it with regular expression matching in java.
我该如何在Java中使用正则表达式匹配。 Thankx.
谢谢。
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]
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);
}
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
...
}
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());
}
这将起作用:
String[] values = s.substring(1).split("\\D+");
"\\\\((\\\\d*),(\\\\d*)\\\\)\\\\s*\\\\((\\\\d*),(\\\\d*)\\\\)"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.