英文:
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$
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论