The Issue

Regular expression in Ruby allows us to interact with an element that contains the value we are looking for in a string, instead of the exact value. In Ruby, a string is a group of letters/characters that constitute readable text, text that we wish to display to someone. A regular expression is a pattern that is matched with the given string, and tells if there is a match or not.  The pattern can be as simple as a single string, or extremely complex. We’ll limit ourselves to a few simple variations that can help a lot in making Watir Webdriver/Selenium Scripts more friendly and flexible.

The Code

The regular expression (a.k.a. regexp) is bounded between forward slashes (/…./).  and is matched against a string object with the ‘=~’ operator. Take a look at the below example:

Here we combine our if/else/then statements and create a script that will fail unless the script finds a story containing /Trump/. We can also insert a local variable into the regexp, using ‘#{variable}’, as seen below:

The Takeaway

Working in Ruby, we can incorporate regular expression into our Watir Webdriver/Selenium automation to add another tool to our validation arsenal. Regular expression provides utility  in Cucumber feature files as well, allowing us to add the same logic to a step definition.