Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression with hyphen in between numbers

Tags:

c#

regex

I have to check whether the user entered string is in a particular format as below eg:

123-1234-1234567-1

ie after first 3 digit a hyphen, then after 4 digit another hyphen, after seven digit an hyphen then a single digit.

I used the below regular expression

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

It is working fine for above expression but it will also pass the expression without - also

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

The second string should fail. What change i should do in the regular expression to achieve the same?

like image 346
Sachu Avatar asked Mar 19 '26 11:03

Sachu


2 Answers

You can simply use:

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

If you want to allow dot and space also as delimiter then use:

^\d{3}[-. ]\d{4}[-. ]\d{7}[-. ]\d$
like image 129
anubhava Avatar answered Mar 22 '26 02:03

anubhava


The problems is that you are having optional quantifier ? after [. ]. Remove them, and it should work fine

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

Regex demo

The ? makes the preceding pattern optional as it matches 0 or 1 character. So in the second example the regex engine safely matches zero - to get to match the entire string

like image 24
nu11p01n73R Avatar answered Mar 22 '26 02:03

nu11p01n73R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!