Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to allow an empty string or a string with specific length

Tags:

regex

Hi I am having trouble trying to create a regex that will allow me to have the field empty or a string with length 9 if populated.

The current regex im using is: ^[0-9]{9}

Which works if the field is mandatory, however we have a new requirement that this can also be empty. I've tried ^[0-9]{0|9} but obviously that doesnt work.

Thanks in advance

like image 625
Redseven Avatar asked Sep 01 '25 03:09

Redseven


1 Answers

^(|[0-9]{9})$

Should do the trick.

Edit: But seriously; do what @Felix Kling suggests in a comment: test the string via a .length property, .equals("") or the like.

like image 54
jensgram Avatar answered Sep 13 '25 19:09

jensgram



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!