不重复最后7位数字的NANP电话号码的正则表达式 [英] Regex for NANP phone number with non-repeating last 7 digits

查看:126
本文介绍了不重复最后7位数字的NANP电话号码的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在.NET中验证NANP格式的10位(美国)电话号码(不允许使用特殊字符),还必须检查以确保电话号码的后7位是不可重复的.到目前为止,我已经编写了以下正则表达式来验证NANP格式

I have to validate a 10 digit (US) phone number in the NANP format (no special characters allowed) in .NET and also check to make sure the last 7 digits of the phone number are non-repeating. So far, I have written the following regex to validate the NANP format

^(?:[2-9][0-8][0-9])([2-9][0-9]{2}[0-9]{4})$

我如何修改此正则表达式以解决非重复的最后7位数字?请注意,由于现有代码的限制,不能选择使用两个正则表达式.

How do I modify this regex to also account for non-repeating last 7 digits? Please note that using two regexes is not an option due to constraints of existing code.

我必须检查所有7位数的连续重复项.例如应该认为2062222222是无效的,而应该认为2062221234或2062117777是有效的.

I have to check for consecutive duplicates in all 7 digits. For e.g. 2062222222 should be considered invalid whereas 2062221234 or 2062117777 should be considered valid.

谢谢

推荐答案

您是在谈论连续重复数字,还是所有七个数字都必须唯一?例如:

Are you talking about consecutive repeating digits, or do all seven digits have to be unique? For example:

2342497553  // consecutive duplicates
2345816245  // non-consecutive duplicates
2345816249  // no duplicates

此正则表达式过滤掉连续的重复项:

This regex filters out consecutive duplicates:

^(?:[2-9][0-8][0-9])(?!.*(\d)\1)([2-9][0-9]{2}[0-9]{4})$

...而此字符不允许任何重复数字:

...while this one disallows any duplicate digits:

^(?:[2-9][0-8][0-9])(?!.*(\d).*\1)([2-9][0-9]{2}[0-9]{4})$

使用完前三个数字后,超前查找会尝试查找立即重复的字符((?!.*(.)\1))或带有可选中间字符((?!.*(.).*\1))的重复字符.而且,这是前瞻,因此,如果成功,则总体匹配失败.

After the first three digits have been consumed, the lookahead tries to find a character that's repeated, either immediately ((?!.*(.)\1)) or with optional intervening characters ((?!.*(.).*\1)). And it's a negative lookahead, so if it succeeds, the overall match fails.

编辑:事实证明,这个问题比我想象的要简单.要过滤出2345555555之类的数字,其中后七个数字相同,请使用以下命令:

It turns out the problem is simpler than I thought. To filter out numbers like 2345555555, where the last seven digits are identical, use this:

^(?:[2-9][0-8][0-9])(?!(\d)\1+$)([2-9][0-9]{2}[0-9]{4})$

包含结束锚($)很重要,因为如果不这样做,它将无法匹配有效的数字,例如2345555556.或者,您可以告诉它查找另外六个捕获的数字:(?!(\d)\1{6}).

It's important to include the end anchor ($), because without that it would fail to match valid numbers like 2345555556. Alternatively, you could tell it to look for exactly six more of the captured digit: (?!(\d)\1{6}).

这篇关于不重复最后7位数字的NANP电话号码的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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