Page 1 of 1

Funky Syntax for validation

Posted: Mon Mar 01, 2004 5:12 pm
by Steveo31
I see this all over the place, and by doing some HW, I can understand some of it, but could someone elaborate to get a clearer view?

Code: Select all

/^[0-9]{5}([-]?[0-9]{4})?$/
I know it is

Numbers 0-9, only 5, a dash, numbers 0-9 again, only 4

But the end syntax and the format of the () is quirkin me.

_S

Posted: Fri Mar 05, 2004 10:46 am
by Wayne
everything in the () is a subpattern of the regular expression the ? means that it must match this pattern either 0 or 1 times, so
([-]?[0-9]{4})? ... means that it must match the - 0 or 1 times followed by 4 digits of 0-9. with that whole subpattern being match 0 or 1 times, the $ at the very end means that there is nothing after.

Posted: Fri Mar 05, 2004 12:25 pm
by Steveo31
Ah nice. Thanks for diggin :)