Regular expressions can help you to do more with your automated tests

Published on January 20, 2025

   “A regular expression defines a set of one or more strings of characters” [1]. Regular expressions (regex) can be used when developing automated tests, for example, by passing a regular expression as a parameter.

If you have not used a regular expression before the MDN Web docs are a good place to start learning about them.

In the examples below a regular expression is used as a function parameter in Playwright.

openMenu() has a regular expression as a parameter, and calls filter() which can take either a string or a regular expression as a parameter. openMenu() could have a string as a parameter but if the parameter is a RegExp we can pass a regular expression to filter (). If we pass a regular expression, instead of a string, as the parameter there are more ways we can use the parameter. 

Here are some examples of how we could pass a regular expression to the function:

/More/ will find an element that has text that contains More:

/^More/ will find an element that has text that starts with More

/More$/ will find an element that has text that ends with More

/More[a-z]/ will find an element that contains More followed by a character in the range a-z

If I had passed the string ’More’ to the function it would have clicked an element that contained More. Passing a regular expression as a parameter gives us more options. 

You can do much more in your automated tests with regular expressions than I have in the examples above. Regular expressions can become complicated, making them hard to read. Testing regular expressions using one of the regex testers listed below is useful. The regex testers not only enable you to test your regex but also explain how it works.

There are so many ways that a regular expression can be used that I find it useful to have points of reference to help. Below there is a list of resources that can be used to help create regular expressions. Please let me know if there are more resources that I have missed

Documentation

Regex Testers

University Course

Regular Expressions (Regex) Nanyang Technological University, Singapore

Blogs

Enhancing Playwright Test Automation with Regular Expressions by Cerosh Jacob

How to Define a Regex-Matched String Type in TypeScript ?

RegEx and Selenium by Tracy O’Connor

cy.contains and regular expressions by  Gleb Bahmutov

Book

A Practical Guide to the UNIX System by Mark G. Sobell (It is rather old, but has a useful appendix on Regular Expressions)

Thank you to Danny Dainton, Christian Bauman and Sebastian Stautz for their help

References
[1] A Practical Guide to the UNIX System by Mark G. Sobell (1995, p735)