Like locators, patterns are a type of parameter frequently used by Selenium. It allows users to describe patterns with the help of special characters. Many a time, the text that we would like to verify are dynamic; in that case, pattern matching is very useful.
Pattern matching is used with all the verification point commands - verifyTextPresent, verifyTitle, verifyAlert, assertConfirmation, verifyText, and verifyPrompt.
There are three ways to define a pattern:
- globbing
- regular expressions, and
- exact patterns.
Globbing
Most techies who have used file matching patterns in Linux or Windows while searching for a certain file type like *.doc or *.jpg. would be familiar with term "globbing"
Globbing in Selenium supports only three special characters: *, ?, and [ ].
* - matches any number of characters.
? - matches a single character.
[ ] - called a character class, lets you match any single character found within the brackets. [0-9] matches any digit.
To specify a glob in a Selenium command, prefix the pattern with the keyword 'glob:'. For example, if you would like to search for the texts "tax year 2013" or "tax year 2014", then you can use the golb "tax year *" as shown below.
However the usage of "glob:" is optional while specifying a text pattern because globbing patterns are the default in Selenium.
Command | Target | Value |
clickAndWait | link=search | |
verifyTextPresent | glob: tax year * | |
Exact Patterns
Patterns with the prefix 'exact:' will match the given text as it is. Let us say, the user wants an exact match with the value string, i.e., without the glob operator doing its work, one can use the 'exact' pattern as shown below. In this example the operator '*' will work as a normal character rather than a pattern-matching wildcard character.
Command | Target | Value |
clickAndWait | link=search | |
verifyValue | exact: *.doc | |
Regular Expressions
Regular expressions are the most useful among the pattern matching techniques available. Selenium supports the complete set of regular expression patterns that Javascript supports. Hence the users are no longer limited by *, ? and [] globbing patterns.
To use RegEx patterns, we need to prefix with either "regexp:" or "regexpi:". The prefix "regexpi" is case-insensitive. The glob: and the exact: patterns are the subsets of the Regular Expression patterns. Everything that is done with glob: or exact: can be accomplished with the help of RegExp.
Example
For example, the following will test if an input field with the id 'name' contains the string 'tax year', 'Tax Year', or 'tax Year'.
Command | Target | Value |
clickAndWait | link=search | |
verifyValue | id=name | regexp:[Tt]ax ([Yy]ear) |