开发者

java parsing a string like "0:ADD(10)"

开发者 https://www.devze.com 2023-01-30 06:22 出处:网络
i am having a string array like this {\"0:ADD(10)\",\"1:ADD(20)\"} how can i parse this and get th开发者_StackOverflow社区e value \'10\',\'20\' from this string ,

i am having a string array like this {"0:ADD(10)","1:ADD(20)"} how can i parse this and get th开发者_StackOverflow社区e value '10','20' from this string ,

Scenario is : i am trying to write a client and server app using Apache Mina server , when i sent message between client and server i am getting response as "0:ADD(10)"


You can use a regular expression like this:

\\((\\d+)\\)

to extract the number from between the brackets. More information on java regex can be found here and here Note: Since java adds, by default, the ^ and $ at the beginning and end respectively, we have to add the .* before and after the pattern we want to match.

String[] str  = new String[]{"0:ADD(10)","1:ADD(20)"};
        Pattern pattern = Pattern.compile("^.*\\((\\d+)\\).*$");
        for (int i = 0; i < str.length; i++)
        {
            Matcher m = pattern.matcher(str[i]);
            System.out.println(m.matches());
            System.out.println(m.group(1));
        }

Prints:

true

10

true

20


    String[] split = "{\"0:ADD(10)\",\"1:ADD(20)\"}".split( "," ); 
    for ( String e : split ) {
        String arg = e.substring( e.indexOf( '(' )+1, e.indexOf( ')') );
         System.out.println( arg );
     }


You can try

int num = Integer.parseInt("0:ADD(10)".split("[()]")[1]);


Might be a bit of overkill, but this should work

    String input="{\"0:ADD(10)\",\"1:ADD(20)\"}";
    Pattern r= Pattern.compile(":ADD\\(([0-9]*)\\)");
    Matcher m = r.matcher(input);
    while(m.find()){
        System.out.println(m.group(1)); //Result is here
    }


Using guava:

String digits=(digits=CharMatcher.DIGIT.retainFrom("0:ADD(10)")).substring(1,digits.length());


this single line does the work:

String[] arr = str.replace("{", "").replace("}", "").replaceAll("\"\\d+:ADD\\((\\d+)\\)\"", "$1").split(",");
0

精彩评论

暂无评论...
验证码 换一张
取 消