所有英国电话号码的正则表达式 [英] regex for all UK telephone numbers

查看:214
本文介绍了所有英国电话号码的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证以下格式的英国电话号码:

I am trying to validate UK telephone numbers, which are in the format of:

01234 567890

01234567890

02012345678

020 1234 5678

我有以下正则表达式,除了020 1234 5678

I have the following regex, which works for all apart from the 020 1234 5678

^\s*\(?(020[7,8]{1}\)?[ ]?[1-9]{1}[0-9{2}[ ]?[0-9]{4})|(0[1-8]{1}[0-9]{3}\)?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{3})\s*$

有人知道这是为什么吗?

Does anyone know why this is?

推荐答案

您缺少右方括号

^\s*\(?(020[7,8]{1}\)?[ ]?[1-9]{1}[0-9{2}[ ]?[0-9]{4})|(0[1-8]{1}[0-9]{3}\)?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{3})\s*$
                                      ^
                                     here

这应该正常工作

^\s*\(?(020[7,8]{1}\)?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{4})|(0[1-8]{1}[0-9]{3}\)?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{3})\s*$

您还可以从表达式中删除一些内容.

Further you can remove some stuff from your expression.

{1}不需要每个字符都匹配一次

{1} is not need every character is still matched once

[ ],只需将其替换为空格

[ ] is also not needed, just replace it with a space

[8,9]是错误的.它将匹配8、9和.使用[89]是正确的.

[8,9] is wrong. it will match 8, 9 and , . Use [89] is correct.

然后看起来像这样

^\s*\(?(020[78]\)? ?[1-9][0-9]{2} ?[0-9]{4})|(0[1-8][0-9]{3}\)? ?[1-9][0-9]{2} ?[0-9]{3})\s*$

如果您想允许这种不匹配的模式 020 1234 5678 ,您可以这样做

If you want to allow this not matched pattern 020 1234 5678 you could do for example

^\s*\(?(020[78]?\)? ?[1-9][0-9]{2,3} ?[0-9]{4})$|^(0[1-8][0-9]{3}\)? ?[1-9][0-9]{2} ?[0-9]{3})\s*$
               ^                 ^^
made the [78] optional        allows no 2 or 3 of `[0-9]`

在Regexr上查看

我不知道这是否是有效的英国电话号码!

I have no clue if this is a valid UK phone number!

我在这里还修复了正则表达式中的另一个错误,在管道|之前缺少$,在管道|之后缺少了^

I fixed here also another bug in the regex a missing $ before and a missing ^ after the pipe |

这篇关于所有英国电话号码的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆