Regular expression with hyphen between digits

I need to check if a custom string is entered in a specific format like below:

123-1234-1234567-1

      

those. after the first 3 digits a hyphen, then after 4 digits another hyphen, after seven digits a hyphen, then one digit.

I used the following regex

@"^\(?([0-9]{3})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{7})[-. ]?([0-9]{1})$"

      

It works fine for the expression above, but it will also pass the expression without -

also

eg:-  123-1234-1234567-1 //pass
      123123412345671    //also getting pass.

      

The second line should fail. What change should I make in the regex to achieve the same?

+3


source to share


2 answers


You can simply use:

^\d{3}-\d{4}-\d{7}-\d$

      



If you want to allow period and space as delimiter as well, use:

^\d{3}[-. ]\d{4}[-. ]\d{7}[-. ]\d$

      

+1


source


The problem is that you have an optional quantifier ?

after [. ]

. Delete them and it should work fine

@"^\(?([0-9]{3})\)?[-. ]([0-9]{4})[-. ]([0-9]{7})[-. ]([0-9]{1})$"

      



Demo Regex

?

makes the previous pattern optional since it matches 0 or 1 characters. So in the second example, the regex mechanism matches zero safely -

to match the entire string

+1


source







All Articles