用于提取电话号码的正则表达式

时间:2014-09-30 10:40:54

标签: java regex

我有以下要求:

数字(按顺序或由连字符空格分隔)

[optional]

之间可以有连字符 -

[optional]

之间可以有空格

可以打开大括号(右括号) [可选]

开头可以有加+ 。 [可选]

现在,我正在使用 (^ |)[0-9。() - +] {5,}(| $)

示例文字:

  

联络亚洲:(11)6530-6596-3242,+ 9145465465465(011)4420717696024 +1 212-904-2860

2 个答案:

答案 0 :(得分:0)

查找电话号码是一个相当困难的问题,因为不同地区的电话号码会有不同的约定。我会建议libphonenumber,这是Google为此开发的一个库。该库包含一个方法findNumbers(CharSequence, String),它可以找到电话号码并以解析的方式返回它们。

String text = "Call me at +1 425 882-8080 for details.";
RegionCode country = RegionCode.US;
PhoneNumberUtil util = PhoneNumberUtil.getInstance();

// Find the first phone number match:
PhoneNumberMatch m = util.findNumbers(text, country).iterator().next();

// rawString() contains the phone number as it appears in the text.
"+1 425 882-8080".equals(m.rawString());

// start() and end() define the range of the matched subsequence.
CharSequence subsequence = text.subSequence(m.start(), m.end());
"+1 425 882-8080".contentEquals(subsequence);

// number() returns the the same result as PhoneNumberUtil.parse()
// invoked on rawString().
util.parse(m.rawString(), country).equals(m.number());

答案 1 :(得分:0)

这可能不适用于所有情况,但您应该有更多的电话号码输入规则,但是您可以尝试一下:[0-9\(\+]+[0-9\)\-]+[, ]?