分割字符串,只获取一个数字数组(转义为白色和空的空格)

时间:2022-04-14 21:42:15

In my scenario, a string is given to my function and I should extract only the numbers and get rid of everything else.

在我的场景中,一个字符串被赋予了我的函数,我应该只提取数字并除去其他的东西。

Example inputs & their expected array output:

示例输入及其预期数组输出:

13/0003337/99  // Should output an array of "13", "0003337", "99"
13-145097-102  // Should output an array of "13", "145097", "102"
11   9727  76  // Should output an array of "11", "9727", "76"

In Qt/C++ I'd just do it as follows:

在Qt/ c++中,我的做法如下:

QString id = "13hjdhfj0003337      90";
QRegularExpression regex("[^0-9]");

QStringList splt = id.split(regex, QString::SkipEmptyParts);

if(splt.size() != 3) {
    // It is the expected input.
} else {
    // The id may have been something like "13 145097 102 92"
}

So with java I tried something similar but it didn't work as expected.

所以我用java做了一些类似的尝试,但没有达到预期的效果。

String id = "13 text145097 102"
String[] splt = id.split("[^0-9]");
ArrayList<String> idNumbers = new ArrayList<String>(Arrays.asList(splt));

Log.e(TAG, "ID numbers are: " + indexIDS.size());  // This logs more than 3 values, which isn't what I want.

So, what would be the best way to escape all spaces and characters except for the numbers [0-9] ?

那么,除了数字[0-9]之外,什么是最好的转义所有空格和字符的方式呢?

1 个解决方案

#1


7  

Use [^0-9]+ as regex to make the regex match any positive number of non-digits.

使用[^ 0 - 9]+作为正则表达式使正则表达式匹配任何non-digits正数。

id.split("[^0-9]+");

Output

[13, 145097, 102]

Edit

Since does not remove trailing the first empty String, if the String starts with non-digits, you need to manually remove that one, e.g. by using:

由于不删除第一个空字符串,如果字符串以非数字开头,则需要手动删除第一个空字符串,例如:

Pattern.compile("[^0-9]+").splitAsStream(id).filter(s -> !s.isEmpty()).toArray(String[]::new);

#1


7  

Use [^0-9]+ as regex to make the regex match any positive number of non-digits.

使用[^ 0 - 9]+作为正则表达式使正则表达式匹配任何non-digits正数。

id.split("[^0-9]+");

Output

[13, 145097, 102]

Edit

Since does not remove trailing the first empty String, if the String starts with non-digits, you need to manually remove that one, e.g. by using:

由于不删除第一个空字符串,如果字符串以非数字开头,则需要手动删除第一个空字符串,例如:

Pattern.compile("[^0-9]+").splitAsStream(id).filter(s -> !s.isEmpty()).toArray(String[]::new);