A regular expression, or regex, is a sequence of characters that forms a search pattern. This pattern can find other strings.
Regexes have their origins in theoretical computer science and are based on mathematical principles. In favor of a more practical approach, we don’t go into the theoretical details of regexes in this chapter. If you would like to learn more about them, many resources on the web offer detailed explanations. The Wikipedia article for regular expressions is a good place to start.
In this chapter, you will learn why regexes are used, get an overview of their syntax, and see how you can apply them in Ranorex Studio.
How regexes work
As mentioned in the introduction paragraph, regexes are basically a search pattern. They act the same way in Ranorex Studio, as a filter mechanism.
In Ranorex Studio, regexes are used in the following areas:
- In RanoreXPath expressions as part of identifying UI elements
- In Validation actions to validate strings
- In Get actions to extract strings
- In weight rule conditions to define the string that needs to be present in a RanoreXPath expression for the condition to be fulfilled
Let’s take a validation as an example to illustrate this. In the validation, check the value of a UI element attribute. The value, for example, the string to be checked, consists of letters and a number. For the validation, only the number is relevant.
Additionally, the number may change as a result of interacting with the AUT. Therefore, the validation must be able to find any number in the string to be robust. A regex accomplishes this:
-
In the AUT, the number of database entries is contained in an alphanumerical string.
-
A filter, for example, the regex, has to find and return only the number from the alphanumerical string.
-
The result of this filtering process is that only the number is passed on to the validation; the rest of the string is ignored.
Regex style
Before continuing with the syntax and examples on the next two pages, let’s take a moment to talk about style in regexes.
As with most formulas or filters, there are often several different regexes you can use to arrive at the same result. Which regex to choose then depends on two factors.
Specific vs. general phrasing
In most cases, it is recommended to phrase regexes so they are more general, for example, apply to more cases. Use specific phrasing if you have a very specific task you want to solve.
Example:
Dynamic IDs often consist of a prefix or suffix and a random string. A regex to catch such dynamic IDs should be as general as possible, so it won’t just identify a particular pattern, for example, only dynamic IDs with a prefix, but not with a suffix.
Detailed vs. minimalistic phrasing
Since regexes are based on mathematical principles, it’s possible to phrase them very minimalistically, for example, with very few characters. This may be economical, but it often makes them harder to read for other people. Keep this in mind when working in a team.