作者:loloyoyo555 | 来源:互联网 | 2023-05-25 18:31
我有一个形式的字符串
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)))
我觉得在每个角色上运行上述方法都是低效的.有没有办法可以获得所有数字的字符串数组?
1> Maroun..:
使用正则表达式(请参阅Pattern
和matcher
):
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher();
while (m.find()) {
//m.group() contains the digits you want
}
您可以轻松构建ArrayList
包含您找到的每个匹配组的内容.
或者,如其他建议,您可以拆分非数字字符(\D
):
"blabla 123 blabla 345".split("\\D+")
注意,\
必须在Java中进行转义,因此需要\\
.