Regex to check number starts with '078'

2020-04-19 08:43发布

问题:

I need to validate a Textbox in my Asp.Net application where the user can enter mobile number and it should starts with 078 and should contain 10 digits.

Sample:

0781234567

here is my code

 public static  bool  CheckPhoneNum(string strPhoneNumber)
    {
        string MatchPhoneNumberPattern = "/^(?=\\d{10,11}$)(07)\\d+/";
        if (strPhoneNumber!= null) return Regex.IsMatch(strPhoneNumber, MatchPhoneNumberPattern );
        else return false;
    }

but it always returns false.

回答1:

Why don't you try this? The below regex would validate for phone numbers which should be starts with 078 followed by any 7 digit number.

^078\d{7}$

DEMO

Explanation:

  • ^ Asserts that we are at the start.
  • 078 Matches exactly the digits 078.
  • \d{7} Matches the following 7 digits.
  • $ End of the line.

IDEONE



回答2:

^078[0-9]{7}$

This is a bit faster than \d if we use only numbers here.