拆分字符串以获取仅数字数组(转义白色和空白空格)

Ala*_*lah 9 c++ java regex qt split

在我的场景中,一个字符串被赋予我的函数,我应该只提取数字并摆脱其他一切.

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

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"
Run Code Online (Sandbox Code Playgroud)

在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"
}
Run Code Online (Sandbox Code Playgroud)

所以使用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.
Run Code Online (Sandbox Code Playgroud)

那么,除了数字[0-9]之外,最好的方法是逃避所有空格和字符?

fab*_*ian 7

使用[^0-9]+的正则表达式来进行匹配的正则表达式的非数字的任何正数.

id.split("[^0-9]+");
Run Code Online (Sandbox Code Playgroud)

产量

[13, 145097, 102]
Run Code Online (Sandbox Code Playgroud)

编辑

由于不会删除尾随第一个空String,如果String以非数字开头,则需要手动删除该数字,例如使用:

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