Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression checking for numeric length

Tags:

regex

I want to validate a zipcode either 5 digit or 9 digit. I've written this /^(\d){5|9}$/ but its not matching anything.

But when i give /^(\d){5}$/ its matching properly for 5.

Please help.

like image 839
Vins Avatar asked Aug 05 '26 21:08

Vins


2 Answers

Make the last four optional:

^\d{5}(\d{4})?$

Note that I removed the opening/closing slashes as they have nothing whatsoever to do with regex; they are an application language artefact.

like image 58
Bohemian Avatar answered Aug 07 '26 14:08

Bohemian


The following regex should work.

^(\d{5}|\d{9})$
like image 35
Hemant Metalia Avatar answered Aug 07 '26 14:08

Hemant Metalia



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!