How to extract numbers from a string

前端 未结 2 1441
我在风中等你
我在风中等你 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 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.

提交回复
热议问题