What is Regular Expression?
Regular expression is a set of symbols (characters) and syntactic elements used to match patterns of text. The term regular expression is often abbreviated to regex or RE.
A regular expression is a way of describing a string of text using metacharacters or wildcard symbols.
A regular expression, often called a pattern, is an expression that describes a set of strings. They are usually used to give a concise description of a set, without having to list all elements.
A quantifier after a token (such as a character) or group specifies how often that preceding element is allowed to occur. Given below are most commonly used quantifiers
1. Period (.) – Matches one character in its position any character(including numbers,special characters) other than /n(new line)
Example : welcome.qtp matches “welcome@qtp”,”welcome2qtp”,”welcome qtp” but not “welcomeqtp”
2. QuestionMark(?) – Matches zero or one occurances of previous character.
Example: goo?gle matches “gogle” and “google”
3. Asterisks(*) – Matches zero,one or many occurances of previous character.
Example: goo*gle matches “gogle”, “google”,”gooogle”,”gooooooooooooooooooogle” etc..
4. Plus(+) – Matches one or more occurances of previous character.
Example: goo+gle matches “google”,”gooogle” etc.. but not gogle
5. Backslash (\): It can be used in conjunction with a special character to indicate that the next character be treated as a literal character
Example: welcomenew\* will literally match “welcomenew*”
6. Caret (^) – Match any character in the list except for the ones specified in the string
Example: [^c]at matches other than cat like bat,rat,@at,2at etc..
7. Pipe (|) – Logical OR
Example: (c|r)at matches cat or rat
8. Square Braces() – Matches the range for anything under that range
Example : [a-z] all lower case,[A-Z] all upper case,[0-9] numbers for 0 to 9
Let us try to come up with a regular expression which allows numbers from 0 to 1200 (this is given in QTP help).We can solve this by having three different patterns first for 0-999,1000-1199 and 1200
( [0-9][0-9][0-9] | [0-9][0-9] | 1200),but the problem here is it will allow to only enter four digits ,so 7 should be entered as 0007 similarly 77 as 0077,so to solve that use ? Quantifier ([0-9]?[0-9]?[0-9] | [0-9][0-9] | 1200).
The Regex Coach is a graphical application for Windows which can be used to experiment with regular expressions interactively. You can download this from http://weitz.de/regex-coach/