查找字符串中的所有数字

问题描述:

例如,我输入字符串: qwerty1qwerty2 ;

For example, I have input String: "qwerty1qwerty2";

作为输出我希望 [1,2 ]

我目前的实施如下:

import java.util.ArrayList;
import java.util.List;

public class Test1 {

    public static void main(String[] args) {
        String inputString = args[0];
        String digitStr = "";
        List<Integer> digits = new ArrayList<Integer>();

        for (int i = 0; i < inputString.length(); i++) {
            if (Character.isDigit(inputString.charAt(i))) {
                digitStr += inputString.charAt(i);
            } else {
                if (!digitStr.isEmpty()) {
                    digits.add(Integer.parseInt(digitStr));
                    digitStr = "";
                }
            }
        }
        if (!digitStr.isEmpty()) {
            digits.add(Integer.parseInt(digitStr));
            digitStr = "";
        }

        for (Integer i : digits) {
            System.out.println(i);
        }
    }
}

但经过仔细检查后我不喜欢几点:

But after double check I dislake couple points:


  1. 某些代码行重复两次。

  1. Some lines of code repeat twice.

我使用List。我认为这不是一个好主意,更好地使用数组。

I use List. I think it is not very good idea, better using array.

那么,你怎么看?

您能提供任何建议吗?

使用RepalceAll

Use RepalceAll

String str = "qwerty1qwerty2";      
str = str.replaceAll("[^0-9]+", " ");
System.out.println(Arrays.asList(str.trim().split(" ")));

输出:

[1, 2]

如果你想包括 - ae减去,添加 - ?

If you want to include - a.e minus, add -?:

String str = "qwerty-1qwerty-2 455 f0gfg 4";      
str = str.replaceAll("[^-?0-9]+", " "); 
System.out.println(Arrays.asList(str.trim().split(" ")));

输出:

[-1, -2, 455, 0, 4]






描述

[^-?0-9]+




  • + 之间一次和无限次,尽可能多次,根据需要回馈

  • - ?其中一个字符 - ?

  • 0-9 0和9之间的字符

    • + Between one and unlimited times, as many times as possible, giving back as needed
    • -? One of the characters "-?"
    • 0-9 A character in the range between "0" and "9"