首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >有办法解决这个分割电话号码的准则吗?

有办法解决这个分割电话号码的准则吗?
EN

Stack Overflow用户
提问于 2022-02-16 11:51:56
回答 1查看 83关注 0票数 1

嗯,这里的初学者..。我有一个用于Pattern.compile的正则表达式:

Pattern pattern = Pattern.compile("^(?:\\+?(\\d{1,3}))?[- ]?(\\d{1,3})?[- ]?(\\d{4,10})$");

它应该与这类电话号码相匹配:

  1. +1234 5678900 /这是你在国际上的拨号方式
  2. +1-234-5678900 // .
  3. 5678900 /这是你在国际上使用00而不是+拨号的方式。
  4. 001-234-5678900 // .
  5. 5678900 /这是你在同一个国家的拨号方式
  6. 0234-5678900 /.
  7. 5678900 //这是你在同一地区拨号的方式

现在,它匹配并正确地拆分了前四个,但是当涉及到选项5、6和7时,我得到了以下信息:

  • Country Code: 0234
  • Local Area Code : 567
  • Number : 8900

这是:

  • Country Code: 567
  • Local Area Code: null
  • Number: 8900

我做错了什么或者错过了什么?

完整的代码:

代码语言:javascript
运行
复制
public static void main(String[] args) {

        String phoneNumber = "+1 234 5678900";
        Pattern p = Pattern.compile("^(?:\\+?(\\d{1,4}))?[- ]?(\\d{1,3})?[- ]?(\\d{4,10})$");
        Matcher m = p.matcher(phoneNumber);

        while (m.find()) {
            printMatch("Country Code", m, 1);
            printMatch("Local Area Code", m, 2);
            printMatch("Number", m, 3);
        }
        
    }

    public static void printMatch(String label, Matcher m, int group) {
        System.out.printf("%-16s: %s%n", label, m.group(group));
    }

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-16 12:11:16

你可以用

代码语言:javascript
运行
复制
Pattern p = Pattern.compile("^(?:\\+?(\\d{1,3}?)[- ]?)??(\\d{1,3})??[- ]?(\\d{4,10})$");

regex演示。请注意,如果对.matches()使用正则表达式,则不需要^$锚点。

详细信息

  • ^ -字符串的开始
  • (?:\+?(\d{1,3}?)[- ]?)?? -一个可选的(懒惰)发生的可选+,然后是一个、两个或三个(但尽可能少的)数字(第1组),然后是可选的-或空格。
  • (\d{1,3})?? -第2组:1或0,但尽可能少地出现1、2或3位数字
  • [- ]? -可选空间或-
  • (\d{4,10}) -第3组:4到10位数
  • $ -字符串的末端。

在Java代码中,您应该使用if而不是while,因为您只需要第一次匹配,请参见下面的演示

代码语言:javascript
运行
复制
import java.util.*;
import java.util.regex.*;
 
class Test
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String phoneNumber = "+1 234 5678900";
        Pattern p = Pattern.compile("(?:\\+?(\\d{1,3}?)[- ]?)??(\\d{1,3})??[- ]?(\\d{4,10})");
        Matcher m = p.matcher(phoneNumber);
 
        if (m.matches()) {
            printMatch("Country Code", m, 1);
            printMatch("Local Area Code", m, 2);
            printMatch("Number", m, 3);
        }
    }
    public static void printMatch(String label, Matcher m, int group) {
        System.out.printf("%-16s: %s%n", label, m.group(group));
    }
}

屈服

代码语言:javascript
运行
复制
Country Code    : 1
Local Area Code : 234
Number          : 5678900
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71141363

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档