简体   繁体   中英

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"

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.

If you are sure about the format of String and it never changes apart from the numbers, you can do something like this.

    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:

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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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