Saturday, September 1, 2007

Regular Expressions

I just realize that chapter 7 of "Professional Javascript For Web Developers" by Wrox in 2005 is a very good chapter that has clear and details explanation of Regular Expression. There are some sorts of things that I need to keep in mind:
1. If you want the exact match, use ^ in the front of the string and use $ at the end of the string. For example, /\d+/ would match "222", "2s2ss", "s989". However, if you want to match only number, use this /^\d+$/.
2. If you use /^\d+$/, floating-point is not passed, so to solve this problem, use this /[0-9]*\.?[0-9]*/. Then you can use ^ and $ before and after the regular expression.
3. If you want to match the pattern like this "1111, 333, 2222". This pattern is dynamic, sometimes have 3, 4, or 5 items. So, use * to make the last item optional. /\d+(, \d+)*/.
4. There are some common regular pattern in this chapter also.
Date validation: /(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/(?:19|20\d{2})/
Email validation: /^(?:\w+\.?)*\w+@(?:\w+\.?)*\w+$/
Visa card and Master card are covered in this chapter also.
5. use \A and \Z to match the start and end of the string, ^ and $ match the start/end of a line.

This website provides more details about Regular Expression. Have a look

No comments:

Subscribe in a Reader