如何从字符串中获取一些数字

时间:2016-01-28 09:47:38

标签: java regex string-parsing

我有这个字符串" 9X1X121:1001,1YXY2121:2001,角色:ZZZZz"并且需要从输入字符串中获取数字。

String input = "9X1X121: 1001, 1YXY2121: 2001, Role: ZZZZz";
String[] part = input.split("(?<=\\D)(?=\\d)");
System.out.println(part[0]);
System.out.println(part[1]);

我只需输出以下数字

1001   2001

2 个答案:

答案 0 :(得分:2)

您可以拆分','然后拆分':'上的拆分字符串,然后检查部分[1]是否为数字(以避免像角色这样的情况)。

String input = "9X1X121: 1001, 1YXY2121: 2001, Role: ZZZZz";
String[] allParts = input.split(", ");
for (String part : allParts) {
    String[] parts = part.split(": ");
    /* parts[1] is what you need IF it's a number */    
}

答案 1 :(得分:2)

您可以简单地使用模式类和匹配器类。这里是示例代码,

    Pattern pattern = Pattern.compile(regexString);
// text contains the full text that you want to extract data
Matcher matcher = pattern.matcher(text);

while (matcher.find()) {
  String textInBetween = matcher.group(1); // Since (.*?) is capturing group 1
  // You can insert match into a List/Collection here
}

测试代码

String pattern1 = ": ";  //give start element
String pattern2 = ",";   //end element
String text = "9X1X121: 1001, 1YXY2121: 2001, Role: ZZZZz";

Pattern p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" +    Pattern.quote(pattern2));
Matcher m = p.matcher(text);



while (m.find()) {
    if (m.group(1).matches("[+-]?\\d*(\\.\\d+)?")) {  //check it's numeric or not
        System.out.println(m.group(1));

    }

}