如何从 android 中的文本中获取数字

How to fetch number from text in android

我想在我的应用程序中使用注册,我应该通过短信向用户手机发送密码和验证码。
但是我应该 从消息中读取 verifyCode 自动设置 号码到 verifyCode EditText.

我的消息格式:

Hi, welcome to our service.

your password
12345

your verifyCode
54321

我该怎么做?请帮助我<3

假设密码和验证码的位数是固定的(一般与默认值相同),我们可以从字符串中提取数字,然后找到有验证码的子串。这个假设是为了简单起见。

String numberOnly= str.replaceAll("[^0-9]", "");
String verifyCode = numberOnly.substring(6);

此处 String verifyCode = numberOnly.substring(6); 获取字符串的最后 5 位数字,即您的验证码。您也可以写 numberOnly.substring(6,10); 以避免混淆。

但是这样很容易出现像StringIndexOutOfBoundsException这样的错误,所以每当你想获取从索引i开始到字符串结尾的子字符串时,总是写numberOnly.substring(i)

有很多方法可以做到这一点。您可以使用一些复杂的 regex 或使用简单的 spilt 方法。

试试这个,

    String str = "Hi, welcome to our service.\n"
            + "\n"
            + "your password \n"
            + "12345\n"
            + "\n"
            + "your verifyCode \n"
            + "54321";

    // Solution #1
    String[] parts = str.split("\n");
    System.out.println(parts[3]);
    System.out.println(parts[6]);

    // Solution #2
    String PAT = "(password|verifyCode)\s+(\d+)";
    Pattern pats = Pattern.compile(PAT);
    Matcher m = pats.matcher(str);
    while (m.find()) {
        String grp = m.group(2);
        System.out.println(grp);
    }