Search code examples
c#regexstringnumbersdigits

Regex must start with specific number, must contain 2 hyphens and must end with 4 digit numbers


I am a bit puzzled on how to achieve this after trying so many times. It needs to start with 2 numbers, first number must be 9, then hyphen, then A-Za-z, then dot, then A-Za-z, then hyphen, and end must have 4 digits.

Simple terms for those who don't understand the question: "9<1 digit here>-<sometext.sometext>-<4digits>"

Problem starts with the character dot in the middle of the string. Here is my regex:

^([9])([a-zA-Z0-9]*-*\.){2}[a-zA-Z0-9]\d{4}$

Example input:

  • 90-Amir.h-8394
  • 91-Hamzah.K-4752

Tried figuring out where to put the syntax for the Regex to detect the character dot. But it is not working.


Solution

  • You can write 9<1 digit here>-<sometext.sometext>-<4digits> as:

    ^9[0-9]-[A-Za-z]+\.[A-Za-z]+-[0-9]{4}$
    

    Explanation

    • ^ Start of string
    • 9[0-9] Match 9 and a digit 0-9
    • - Match =
    • [A-Za-z]+\.[A-Za-z]+ Match 1+ chars A-Za-z then . and again 1+ chars A-Za-z
    • -[0-9]{4} Match - and 4 digits
    • $ End of string

    See a regex demo.