在我的场景中,给函数提供了一个字符串,我应该只提取数字并去除所有其他内容。
示例输入及其期望的数组输出:
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);
关于java - 拆分字符串以仅获取数字数组(转义空白和空白),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36113266/