【问题标题】:How to detect and read phone number from user sms message如何从用户短信中检测和读取电话号码
【发布时间】:2018-08-01 20:47:13
【问题描述】:

我正在构建一个从用户短信中读取电话号码的应用程序,我说的不是发件人电话号码,而是消息中的一个号码。

查看下面的示例消息;

“你好!您将1GB转移到2348062570000成功,您的新余额为3072.0MB”

我对号码 2348062570000 感兴趣,这类似于 Whatsapp 如何从用户聊天中识别呼叫号码,任何可以解决问题的库或字符串操作将不胜感激。

【问题讨论】:

  • 您是否正在寻找任何电话号码或特定格式?如果您可以使用它但无法使用 XXX-XXXX 或其他格式,那么它相当容易 - 只需使用正则表达式来连续查找正确的位数。如果您正在寻找任何电话号码,那就更难了。
  • 电话号码和消息在该格式中是恒定的,正则表达式将包含不属于电话号码的数字“3072.0”。 @GabeSechan
  • 任何数字的正则表达式都可以。特定位数的正则表达式不会。不允许 '.' 的正则表达式也不会。在号码中。
  • 你能举个例子@GabeSechan

标签: java android string android-studio sms


【解决方案1】:

以下代码将从字符串中提取所有 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;
}

您可以打印数字:

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

【讨论】:

    【解决方案2】:

    如果您确定 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]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-28
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多