C#正则表达式的电话号码查询电话号码查询、正则表达式

2023-09-03 17:13:14 作者:我若不勇敢,谁来替我坚强

我有以下来检查电话号码按以下格式  (XXX)XXX-XXXX。下面code总是返回true。不知道为什么。

 匹配匹配= Regex.Match(输入@((\(\ D {3} \))|?(\ d {3}  - ))\ D { 3}  -  \ D {4});

    //下面code总是返回true
    如果(match.Success){....}
 

解决方案

这不的总是的匹配,但将匹配的任意字符串包含的三位数字,随后一个连字符,后面四个数字。它也将匹配,如果有东西,看起来像在了前面的区域code。因此,这根据你的正则表达式是有效的:

  %%%%%%%%%%%%%%(999)123-4567 %%%%%%%%%%%%%%%%%
 

要验证字符串中包含一个电话号码的,并没有别的的,你需要添加的锚中在正则表达式的开始和结束时:

  @^((\(\ D {3} \))?|(\ d {3}  - ))?\ d {3}  -  \ d {4} $
 
用js的正则表达式检测电话号码,要求必须是1开头,只能是11位数字,该正则表达式怎么写

I have the following to check if the phone number is in the following format (XXX) XXX-XXXX. The below code always return true. Not sure why.

   Match match = Regex.Match(input, @"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}");

    // Below code always return true
    if (match.Success) { ....}

解决方案

It doesn't always match, but it will match any string that contains three digits, followed by a hyphen, followed by four more digits. It will also match if there's something that looks like an area code on the front of that. So this is valid according to your regex:

%%%%%%%%%%%%%%(999)123-4567%%%%%%%%%%%%%%%%%

To validate that the string contains a phone number and nothing else, you need to add anchors at the beginning and end of the regex:

@"^((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}$"