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

Split string to get an array of digits only (escaping white & empty spaces)

本文关键字:空白 转义 空格 数组 字符串 获取 数字 拆分      更新时间:2023-10-16

在我的场景中,我的函数被赋予了一个字符串,我应该只提取数字并摆脱其他所有内容。

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

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"

在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"
}

所以使用 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.

那么,转义除数字 [0-9] 以外的所有空格和字符的最佳方法是什么?

使用 [^0-9]+ 作为正则表达式,使正则表达式匹配任何正数的非数字。

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

输出

[13, 145097, 102]

编辑

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

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