How to extract numbers from a string

前端 未结 2 1440
我在风中等你
我在风中等你 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();
    
    0 讨论(0)
  • 2021-01-26 10:08

    Use regular expression to find what you want:

    String a = "sin(23)+cos(4)+2!+3!+44!";
    
    Pattern pattern = Pattern.compile("\\d+!"); //import java.util.regex.Pattern
    Matcher matcher = pattern.matcher(a);       //import java.util.regex.Matcher
    while (matcher.find()) {
        System.out.print("Start index: " + matcher.start());
        System.out.print(" End index: " + matcher.end() + " -> ");
        System.out.println(matcher.group());
    }
    

    Output:

    Start index: 15 End index: 17 -> 2!
    Start index: 18 End index: 20 -> 3!
    Start index: 21 End index: 24 -> 44!
    

    Further improvement:

    With the following, you can cast the matcher.group(1) return value directly using Integer.parseInt():

    Pattern pattern = Pattern.compile("(\\d+)!");
    ...
        System.out.println(matcher.group(1));
    

    Output:

    Start index: 15 End index: 17 -> 2
    Start index: 18 End index: 20 -> 3
    Start index: 21 End index: 24 -> 44
    

    Can you figure out the rest? You could use the index values to replace the matches in the original string, but be sure to start from the last one.

    0 讨论(0)
提交回复
热议问题