正则表达式未匹配电话号码示例中的一个案例。

huangapple go评论45阅读模式
英文:

Regex not matching one example of a telephone number

问题

这个正则表达式匹配电话号码,并且可以匹配以下格式:

  • 01234 567 890
  • 01234 567890
  • +441234567890
  • (555) 555-1234
  • (555)5551234

但是它无法匹配:

  • 441234567890

这是因为它缺少前面的加号,与+441234567890的例子相同,只是没有加号。

英文:

I have spent time creating a regular expression, but have got to a point where I am struggling to fix one last issue with it.

This regex matches telephone numbers, and it works for following formats:

  • 01234 567 890
  • 01234 567890
  • +441234567890
  • (555) 555-1234
  • (555)5551234

Regex:

/\s*(([+](\s?\d)([-\s]?\d)|0)?(\s?\d)([-\s]?\d){9}|[(](\s?\d)([-\s]?\d)+\s*[)]([-\s]?\d)+)\s*/;

But this does not match:

441234567890

It's the same as one of the examples above, +441234567890 but without the +.

答案1

得分: 1

这对我来说适用于你提供的所有示例:

/\s*(([+]{0,1}(\s?\d)([-\s]?\d)|0)?(\s?\d)([-\s]?\d){9}|[(](\s?\d)([-\s]?\d)+\s*[)]([-\s]?\d)+)\s*/;

我在[+]后面添加了**{0,1}**,这样它将匹配单个或没有+(实际上也可以使用**[+]?**来实现)。
英文:

This works for me for all of your examples:

/\s*(([+]{0,1}(\s?\d)([-\s]?\d)|0)?(\s?\d)([-\s]?\d){9}|[(](\s?\d)([-\s]?\d)+\s*[)]([-\s]?\d)+)\s*/;

I've added {0,1} after the [+], so that it will match either a single or no + (which could actually also be done by using [+]? )

答案2

得分: 0

在我的情况下,类似这样的内容有效:

^(\d | \ + | \()?(\d)+(\s | \))?(\s)?(\d(\s | -)?)+ \ d $

英文:

In my case something like this works:

^(\d|\+|\()?(\d)+(\s|\))?(\s)?(\d(\s|-)?)+\d$

huangapple
  • 本文由 发表于 2023年6月29日 17:02:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76579593.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定