我想从字符串中提取手机号码。
示例字符串为“嗨,您的手机号码是:9876499321。”
现在我想从字符串中提取“9876499321”。我的主字符串可以在字符串内包含 +919876499321 或 919876499321 或 09876499321 以及其他单词。如何实现这一目标?
我想要的规则:
- 首先删除所有“-”
- 然后提取 10 位到 14 位(含)范围内的数字
我已经尝试过这个:
String myregex = "^\\d{10}$";
Pattern pattern = Pattern.compile(myregex);
Matcher matcher = pattern.matcher(inputStr);
while (matcher.find()) {
System.out.println(matcher.group());
}
我找不到任何匹配项。
最佳答案
您可以在将字符串传递给 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
(?<!\d)\d{10,14}(?!\d)
仅当 10 到 14 个数字未用其他数字括起来时,pattern 才会匹配这些数字。
关于java - 使用正则表达式从字符串中提取手机号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56655381/