how to extract numeric values from input string in java

后端 未结 15 1759
说谎
说谎 2020-12-13 16:25

How can I extract only the numeric values from the input string?

For example, the input string may be like this:

String str=\"abc d 1234567890pqr 548         


        
相关标签:
15条回答
  • 2020-12-13 17:05
    public static List<String> extractNumbers(String string) {
        List<String> numbers = new LinkedList<String>();
        char[] array = string.toCharArray();
        Stack<Character> stack = new Stack<Character>();
    
        for (int i = 0; i < array.length; i++) {
            if (Character.isDigit(array[i])) {
                stack.push(array[i]);
            } else if (!stack.isEmpty()) {
                String number = getStackContent(stack);
                stack.clear();
                numbers.add(number);
            }
        }
        if(!stack.isEmpty()){
            String number = getStackContent(stack);
            numbers.add(number);            
        }
        return numbers;
    }
    
    private static String getStackContent(Stack<Character> stack) {
        StringBuilder sb = new StringBuilder();
        Enumeration<Character> elements = stack.elements();
        while (elements.hasMoreElements()) {
            sb.append(elements.nextElement());
        }
        return sb.toString();
    }
    
    public static void main(String[] args) {
        String str = " abc d 1234567890pqr 54897";
        List<String> extractNumbers = extractNumbers(str);
        for (String number : extractNumbers) {
            System.out.println(number);
        }
    }
    
    0 讨论(0)
  • 2020-12-13 17:06

    You could do something like:

    Matcher m = Pattern.compile("\\d+").matcher(str);
    while (m.find()) {
       System.out.println(m.group(0));
    }
    
    0 讨论(0)
  • 2020-12-13 17:07

    You want to discard everything except digits and spaces:

    String nums = input.replaceAll("[^0-9 ]", "").replaceAll(" +", " ").trim();
    

    The extra calls clean up doubled and leading/trailing spaces.

    If you need an array, add a split:

    String[] nums = input.replaceAll("[^0-9 ]", "").trim().split(" +");
    
    0 讨论(0)
提交回复
热议问题