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

How get the some numbers from the string

我有这个字符串“9X1X121: 1001, 1YXY2121: 2001, Role: 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

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

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 */    
}

你可以简单地使用模式class和匹配器class。下面是示例代码,

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

    }

}