Monday, April 28, 2008

Regular Expression Help

I got an regualr expression question today from one of my friends.  Basically she was using a regular expression  to validate a number was 4 or 6 digits long but the expression she was using ^\d{4,6}$ would validate numbers 5 digits long.  Lets look at this regular expression ^ means starts with. The \d means number and the {4,6} means 4 to 6 digits long.  The $ means ends with. The answer is to use a regular express with an or (the | means or)
Dim regNum As New Regex("^\d{4}$|^\d{6}$")
Debug.Print(regNum.IsMatch("1234").ToString)
Debug.Print(regNum.IsMatch( "12345").ToString)
Debug.Print(regNum.IsMatch("123456").ToString)
Output
True
False

True

No comments:

Post a Comment