How to extract numbers from a string

前端 未结 2 1439
我在风中等你
我在风中等你 2021-01-26 09:39
String a = \"sin(23)+cos(4)+2!+3!+44!\";
a.replaceAll(\"\\D\"); //Not working it is only extracting Digits 

I want to extract the numbers which are wit

2条回答
  •  [愿得一人]
    2021-01-26 09:56

    First thing: Strings are immutable. You code you tried should be more like

    a = a.replaceAll("\\D",""); 
    

    Second, if you are sure that you will not have more complext expressions like ((1+2)!+3)! then you can use appendReplacement and appendTail methods from Matcher class.

    String a = "sin(23)+cos(4)+2!+3!+44!";
    
    StringBuffer sb = new StringBuffer();
    Pattern p = Pattern.compile("(\\d+)!");
    Matcher m = p.matcher(a);
    while(m.find()){
        String number = m.group(1);//only part in parenthesis, without "!"
        m.appendReplacement(sb, calculatePower(m.group(number )));
    }
    m.appendTail(sb);
    a = sb.toString();
    

提交回复
热议问题