Extract Integer Part in String

后端 未结 8 2121
灰色年华
灰色年华 2020-11-27 06:38

What is the best way to extract the integer part of a string like

Hello123

How do you get the 123 part. You can sort of hack it using Java\

8条回答
  •  孤城傲影
    2020-11-27 06:43

    I had been thinking Michael's regex was the simplest solution possible, but on second thought just "\d+" works if you use Matcher.find() instead of Matcher.matches():

    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    
    public class Example {
    
        public static void main(String[] args) {
            String input = "Hello123";
            int output = extractInt(input);
    
            System.out.println("input [" + input + "], output [" + output + "]");
        }
    
        //
        // Parses first group of consecutive digits found into an int.
        //
        public static int extractInt(String str) {
            Matcher matcher = Pattern.compile("\\d+").matcher(str);
    
            if (!matcher.find())
                throw new NumberFormatException("For input string [" + str + "]");
    
            return Integer.parseInt(matcher.group());
        }
    }
    

提交回复
热议问题