将数字提取到字符串数组中

use*_*505 2 java regex arrays string

我有一个形式的字符串

String str = "124333 is the otp of candidate number 9912111242. 
         Please refer txn id 12323335465645 while referring blah blah.";
Run Code Online (Sandbox Code Playgroud)

我需要124333,991211124212323335465645在一个字符串数组.我试过这个

while (Character.isDigit(sms.charAt(i))) 
Run Code Online (Sandbox Code Playgroud)

我觉得在每个角色上运行上述方法都是低效的.有没有办法可以获得所有数字的字符串数组?

Mar*_*oun 9

使用正则表达式(请参阅Patternmatcher):

Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(<your string here>);
while (m.find()) {
    //m.group() contains the digits you want
}
Run Code Online (Sandbox Code Playgroud)

您可以轻松构建ArrayList包含您找到的每个匹配组的内容.

或者,如其他建议,您可以拆分非数字字符(\D):

"blabla 123 blabla 345".split("\\D+")
Run Code Online (Sandbox Code Playgroud)

注意,\必须在Java中进行转义,因此需要\\.