拆分字符串以仅获取数字数组(转义空白和空格)
Split string to get an array of digits only (escaping white & empty spaces)
在我的场景中,我的函数被赋予了一个字符串,我应该只提取数字并摆脱其他所有内容。
示例输入及其预期的数组输出:
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);
相关文章:
- 无法通过空白将文本文件行分隔为矢量
- 如何用转义符替换字符串中的所有特殊字符
- 由cin中的字符串中未捕获空白引起的分割错误
- 如何在C++中将 Python 字符串转换为其转义版本?
- 尝试从 XamlApplication 编译 C++/WinRT 空白应用程序时,我收到未解析的外部符号 winrt_make_*
- 如何在C++中用'\'替换''来处理转义序列?
- 代码精简版页面变为空白
- 如何解释C++字符串中的 \u 转义码?
- 在OpenCV C++中创建空白图像
- Gtkmm 窗口为空白,不显示任何小部件或标题
- PostgresSQL - SQL Ready 语句与字符串转义,防止 SQL 注入攻击
- 我如何使它,无论用户用空白字符串按 Enter 多少次,它总是打印"开始"字符串?
- 有没有办法获取用户操作系统的ANSI转义码?
- OpenGL - 添加第二个着色器属性会导致空白屏幕
- 对象数组打印空白字符串
- 是否可以在原始字符串文本中插入转义序列?
- 为什么当我从 cin 阅读时转义字符不起作用?
- 使用无法适应其相关类型的转义序列
- 在 boost::fs::p ath 中转义空白
- 拆分字符串以仅获取数字数组(转义空白和空格)