简体   繁体   English

如何从用户短信中检测和读取电话号码

[英]How to detect and read phone number from user sms message

I'm building an application that read phone number from user sms message, i'm not talking about the sender phone number but a number inside the message. 我正在构建一个应用程序,该应用程序从用户短信中读取电话号码,我不是在说发件人电话号码,而是消息中的号码。

Check the example message below; 检查以下示例消息;

"Y'ello!, your transfer of 1GB to 2348062570000 was successful and your new balance is 3072.0MB" “您好!您已成功将1GB传输到2348062570000,新余额为3072.0MB”

I'm interested in the number 2348062570000, this is similar to how Whatsapp identify calling number from user chat, any library or string manipulation that could solve the problem will be appreciated. 我对号码2348062570000感兴趣,这类似于Whatsapp从用户聊天中识别呼叫号码的方式,可以解决该问题的任何库或字符串处理将不胜感激。

If you are sure about the format of String and it never changes apart from the numbers, you can do something like this. 如果您确定String的格式,并且它永远不会改变数字,则可以执行以下操作。

    String str = "Y'ello!, your transfer of 1GB to 2348062570000 was 
    successful and your new balance is 3072.0MB" +;

    String[] split = str.split(" ");
    String stringPrecedingPhoneNumber = "to";
    int index = IntStream.range(0, split.length)
            .filter(i -> stringPrecedingPhoneNumber.equals(split[i]))
            .findFirst()
            .orElse(-1);
    System.out.print(split[index +1]);

The following code will extract all the 13 digit numbers out of a string and put them in an ArrayList: 下面的代码将从字符串中提取所有13位数字,并将它们放入ArrayList中:

public static ArrayList<String> getPhones(String s) {
    String regex = "[0-9]{13}";

    ArrayList<String> array = new ArrayList<String>();

    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(s);

    while (matcher.find()) {
        array.add(s.substring(matcher.start(), matcher.end()));
    }

    return array;
}

You can print the numbers: 您可以打印数字:

    String s = "Y'ello!, your transfer of 1GB to 2348062570000 was successful and your new balance is 3072.0MB";
    ArrayList<String> array = getPhones(s);
    for (String phone : array) {
        System.out.println(phone);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM