Extract Integer Part in String

后端 未结 8 2128
灰色年华
灰色年华 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:39

    Assuming you want a trailing digit, this would work:

    import java.util.regex.*;
    
    public class Example {
    
    
        public static void main(String[] args) {
            Pattern regex = Pattern.compile("\\D*(\\d*)");
            String input = "Hello123";
            Matcher matcher = regex.matcher(input);
    
            if (matcher.matches() && matcher.groupCount() == 1) {
                String digitStr = matcher.group(1);
                Integer digit = Integer.parseInt(digitStr);
                System.out.println(digit);            
            }
    
            System.out.println("done.");
        }
    }
    

提交回复
热议问题