简体   繁体   English

如何在Java中使用split从字符串中获取值

[英]How to get values from string with split in java

I have a string having key and value: 我有一个具有键和值的字符串:

A=1,B=2,C=3,D=4,E=5

I need a split regex in java to get these values (1,2,3,4,5) from above string. 我需要在Java中使用正则表达式来从上述字符串中获取这些值(1,2,3,4,5)

You can use regex with this pattern [0-9]+ 您可以将正则表达式与此模式结合使用[0-9] +

Example: 例:

    String toIndex = "A=1,B=2,C=3,D=4,E=5";
    Pattern p = Pattern.compile("[0-9]+");
    Matcher m = p.matcher(toIndex);
    while (m.find()) {
        System.out.println(m.group());
    }

and in the while instead of printing the groups add then to a list or similar for latter manipulation 然后在一段时间内而不是打印组,然后将其添加到列表或类似列表中以供以后操作

use this: 用这个:

    String s = "A=1,B=2,C=3,D=4,E=5";
    Pattern p = Pattern.compile("=(\\d+)");

    Matcher m = p.matcher(s);
    while (m.find()) {
        System.out.println(m.group(1));
    }

\\d+ is for one until n digits \\ d +表示一位直到n位数字

Since you asked to use split, this will work as well. 由于您要求使用split,因此也可以使用。

    String str2 = "A=1,B=2,C=3,D=4,E=5";
    String [] between = str2.split("=+|,");
    for(int i=1; i<between.length; i+=2){
        System.out.println(between[i]);
    }

Works for both strings and numbers between = and , 适用于=和之间的字符串和数字

(A=AA,B=BB,C=CC,D=DD,E=EE) (A = AA,B = BB,C = CC,d = DD,E = EE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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