我有一个格式为
的字符串String str = "124333 is the otp of candidate number 9912111242.
Please refer txn id 12323335465645 while referring blah blah.";
我需要字符串数组中的 124333
、9912111242
和 12323335465645
。我已经尝试过这个
while (Character.isDigit(sms.charAt(i)))
我觉得对每个角色都运行上述方法效率很低。有没有办法获得所有数字的字符串数组?
最佳答案
使用正则表达式(请参阅 Pattern
和 matcher
):
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(<your string here>);
while (m.find()) {
//m.group() contains the digits you want
}
您可以轻松构建包含您找到的每个匹配组的ArrayList
。
或者,正如其他建议的那样,您可以拆分非数字字符 (\D
):
"blabla 123 blabla 345".split("\\D+")
请注意,\
在 Java 中必须进行转义,因此需要 \\
。
关于java - 将数字提取到字符串数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28062658/