正则表达式用于澳大利亚电话号码验证 [英] Regex for Australian phone number validation
问题描述
我尝试使用以下正则表达式进行电话号码验证,但无法正常工作,
I tried below regex for phone numbers validation but did not work properly,
^([+61|0](2|4|3|7|8|)){0,2}([ 0-9]|[(]){2,3}([)]|[0-9]){6}([ ])[0-9]{7,20}$
以下是我希望通过验证的示例
Here are examples I expect to pass validation
+61(02)89876544
+61 2 8986 6544
02 8986 6544
+61289876544
0414 570776
0414570776
0414 570 776
+61 414 570776
+61 (0)414 570776
以下字符也可以接受。
() - + space
below characters also be accepted. ()-+ space
推荐答案
这就是电话号码结构。最简单的解决方案是要求用户以特定格式输入或让表单自动格式化。如果你必须使用正则表达式,这就是我提出的:
That's quite the phone number structure. The easiest solution is to ask the user to input in a particular format or have the the form automatically format it. If you must use a regex, this is what I came up with:
^(?:\+?(61))? ?(?:\((?=.*\)))?(0?[2-57-8])\)? ?(\d\d(?:[- ](?=\d{3})|(?!\d\d[- ]?\d[- ]))\d\d[- ]?\d[- ]?\d{3})$
捕获组:
- 国家代码(可选)
- 区域/提供者代码(可选)
- 电话号码
演示: https://regex101.com/r/dkFASs/6
这就是我以前用过的确定格式: https://en.wikipedia.org/wiki/Telephone_numbers_in_Australia
This was what I used to nail down the format: https://en.wikipedia.org/wiki/Telephone_numbers_in_Australia
当处理这样一个更大的正则表达式时,我发现最常用的方法是将你的测试用例粘贴到像 regex101.com 然后按捕获组捕获组(如果可以的话,命名它们),直到结束。一旦一组不匹配,就改变你已经拥有的东西。
When tackling a larger regex like this, I find the esiest way is to stick your test cases into a tool like regex101.com and then go capture group by capture group (naming them if you can) until you get to the end. As soon as one group doesn't match, change what you already have until it does.
这篇关于正则表达式用于澳大利亚电话号码验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!