【问题标题】:Extract mobile number from string using regex使用正则表达式从字符串中提取手机号码
【发布时间】:2019-06-18 18:54:54
【问题描述】:

我想从字符串中提取手机号码。
示例字符串为"Hi, Your Mobile no. is: 9876499321."

现在我想从字符串中提取“9876499321”。我的主字符串可以在字符串中包含 +919876499321 或 919876499321 或 09876499321 以及其他单词。如何做到这一点?

我想要的规则:

  1. 首先删除所有“-”
  2. 然后提取范围从10位到14位(含)的数字

我试过这个:

String myregex = "^\\d{10}$";
Pattern pattern = Pattern.compile(myregex);
Matcher matcher = pattern.matcher(inputStr);

while (matcher.find()) {
    System.out.println(matcher.group());
}

我找不到任何匹配项。

【问题讨论】:

  • 尝试"\\d{10}\\b" 获取独立号码的最后 10 位数字。这里的实际规则是什么?
  • 如果我想从号码(例如 91-923223)中删除任何“-”怎么办?
  • 如果您提供所有可能的案例/解释确切数量的规则以提取您想要的文本怎么办?
  • @WiktorStribiżew 编辑了我的问题
  • 尝试 1) Matcher matcher = pattern.matcher(inputStr.replace("-", "")) 和 2) "\\b\\d{10,14}\\b""(?<!\\d)\\d{10,14}(?!\\d)" 正则表达式。

标签: java android regex


【解决方案1】:

您可以在将字符串传递给 pattern.matcher 之前删除所有连字符,然后匹配 10 到 14 位的独立数字:

String inputStr = "Hi, Your Mobile no. is: 9876499321. Also, +919876499321 or 919876499321 or 09-876499321.";   
String myregex = "(?<!\\d)\\d{10,14}(?!\\d)";
// Or String myregex = "\\b\\d{10,14}\\b";
Pattern pattern = Pattern.compile(myregex);
Matcher matcher = pattern.matcher(inputStr.replace("-", ""));

while(matcher.find()) {
    System.out.println(matcher.group());
}

Java demo,输出:

9876499321
919876499321
919876499321
09876499321

(?&lt;!\d)\d{10,14}(?!\d) 模式仅匹配 10 到 14 位数字,前提是它们没有被其他数字包围。

【讨论】:

    【解决方案2】:

    如果始终是 10+ 位字符串的最后 10 位,您可以执行以下操作:

    String myregex = "^.*(\\d{10})([^\\d].*|$)";

    并使用matcher.group(0) 而不是matcher.group()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-27
      • 2014-10-17
      • 1970-01-01
      • 2014-08-25
      • 1970-01-01
      • 2010-10-14
      相关资源
      最近更新 更多