Regular Expressions: Common elements part 2 (Range Search)

I had covered following components in last chapter of common elements
- ^(Start),
- $(End),
- .(Any char),
- *( zero or more occurrences),
- +( one or more occurrences) and
- ?( zero or one occurrences)
Range Search
Range search let you search for specified characters or their range. You need to enclose all characters with in square brackets as follows
[abcd987ABCD]
Example
[0123456789]+
You can use above RE for mobile number searching. However, there are two things wrong with this RE.
1) If characters increased then length of RE is increased
2) Mobile numbers are generally 10 digits. While this RE will search all numeric words contain at least 1 digit.
Lets resolve these issues,
| [0-9] | It means any character from 0 to 9. |
| [a-z] | any character from a to z. |
| [A-Z] | any character from A to Z. |
You can limit the range like ,[01] or [A-J].
Or you can combine them as [a-z0-9A-U].
You can also use some special characters, back slashes characters and spaces like [a-z@\. \t]
Examples
1. Search for all CAPITAL Words.
[A-Z]+
2. Search for Moblie numbers
[0-9]+
3. Search for email ids (An email id can contain “.”,”_”. And website name can contain “-“ )
[a-z0-9\_\.]+@[a-z0-9\-]+\.[a-z]+
[^0-9]*
Above RE will search for every character excluding numeric chars.
*, + are used to set minimum occurrence. We can define maximum or minimum limit of occurrences of RE.
| r{m} | exact m occurrences of r |
| r{m,} | at least m occurrences of r |
| r{n,m} | n to m occurrences of r |
Examples
Mobile number has 10 fixed digits.
[0-9]{10}
Domain name should be less than 5 characters.
[a-z0-9\_\.]+@[a-z0-9\-]+\.[a-z]{2,5}
views


No Comments