简体   繁体   中英

How get the some numbers from the string

I have this string "9X1X121: 1001, 1YXY2121: 2001, Role: ZZZZz" and need to get the numbers from the input string.

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

I need output as below numbers only

1001 2001

You could split on ',' then split the splitted String on ': ' and then check if the part[1] is number or not (to avoid cases like 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 */    
}

You can simply use pattern class and matcher class for it. here below the sample code,

    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
}

test code

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

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM