Regular Expressions: An Introduction
Published: January 12, 2004
User Rating: 8.9 (274 votes)
As mentioned earlier, Sub-patterns are patterns within patterns. Sub-patterns are defined by putting the pattern in simple brackets ( )
So, whatever we have discussed for the patterns, is valid for sub-patterns. And yes, that means that sub-patterns can themselves have more nested sub-patterns.
Using sub-patterns, you can design very powerful regexps for the matching.
To sum up what we have discussed in this article, we will design a regular expression for matching a valid email address. For our test, we would assume that a valid email address
- Must start with an alphabet
- Followed by alphanumeric, including underscore (_), dash (-) and dot (.)
- Followed by the at the rate (@)
- Followed by alphanumeric, including dash(-)
- Followed by dot (.)
- Followed by top level domain (i.e. alphabet with minimum 2 and maximum 4 characters)
- Should be case-insensitive
- Should only match the above rules when the email address is NOT EMPTY
even though real email addresses may differ from this.
So, putting, everthing in action, we would be going step by step. Each steps pattern has been made bold so that you can understand clearly.
Please note that there are better ways to define an regexp for matching the valid email address than what has been listed above, but using the above method, you would have learnt everything