在 Android Studio 中只读取 OTP SMS 中的数字

Read only digit from OTP SMS in Android Studio

我正在尝试从 android 中的 SMS 中读取 OTP。我能够收到完整的消息。但是,我只需要来自 SMS 的 OTP。

请为此提出任何解决方案。 谢谢

当获取整个短信时使用此方法获取 OTP:

                    final Pattern p = Pattern.compile( "(\d{4})" );
                    final Matcher m = p.matcher(messages[0].getMessageBody());
                    if ( m.find() ) {
                        Log.e("SMSotp", String.valueOf(m.group()));
                    }
                    String[] singleCHAR= m.group().split("(?!^)");

在这里,如果你的OTP是n位那么使用,(\d{n}) in Pattern compile

试试这个

smsString = smsString.replaceAll("\D+","");

它将从 smsString

中删除非数字