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?
source to share
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})$"
?
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
source to share