Monday, April 08, 2013

Basic Regular Expression Patterns IV

1. Problem : Check for a 10 digit long mobile phone number that starts with either 9 or 8
   Answer  :
   var patt = /^(8|9)[0-9]{9}$/;
 patt.test("6547896520");  // False
 patt.test("9547896520");  // True


  Explanation :
   a. (8|9) means the string must start with either 8 or 9
   b. [0-9]{9} means after the initial digit 8 or 9, a sequence of 9 digits should appear.
     
2. Problem : Check whether a number is between 0 to 199
   Answer  :
   var patt = /^[1]?[0-9]?[0-9]{1}$/;
 patt.test("500"); //false
 patt.test("100"); //True


   Explanation :
   a. [1] means the string may start with 1 at hundreds position. Remember the number can go maximum 199.
   b. [0-9]? means, next digit at tens position can be any digit between 0 and 9. "?" means this may or may not appear.
   c. [0-9]{1} means at unit position, 1 digit must appear.

   So, numbers like "1" or "33" or "167" is captured as valid whereas "234" would be treated as invalid. The above REGEXP would allow "0" or "00" as a valid. To make the range 1 to 199 we would require some more complex REGEXP which will be discussed next.

3. Problem : Check whether a number is between 1 to 199
   Answer  :
   var patt = /^([1-9]{1}|[1-9][0-9]|[1][0-9][0-9])$/; 
 patt.test("210"); //false
 patt.test("100"); //True


   Explanation :
   a. [1-9]{1} means the string may be a single digit number ranging from 1 to 9 only. Zero won't be captured here.
   b. | means OR. We are checking multiple patterns at a time, if any of them is matched the result is TRUE.
   c. [1-9][0-9] means the string may be a double digit number ranging between 10 to 99.
   d. [1][0-9][0-9] means the string may be a 3-digit number ranging between 100 to 199 only, as [1] ensures the number must start with 1. Hence number 200 onwards are discarded.


Check next part of this article here.

No comments: