In Cucumber, It is easy to write the step glue code without any regular expression knowledge because Cucumber has feature that auto generate your step definition from a step you typed in feature file.
But I suggest you should learn some basic regular expression syntax. Well-crafted regular expressions let you reuse step definitions, avoiding duplication and keeping your tests maintainable. It is the key to Cucumber’s flexibility.
Now let’s start learn some basic Regex:
1. Anchors
Given("^the user logged in as administrator$", () -> {}
The caret at the beginning anchors to the beginning of the string. The dollar at the end does the same with the end of the string.
What’s happen if you don’t include these anchors ?
When you try to access step definition of the user logged in , you IDE will matches and show you 2 steps: the user logged in and the user logged in as administrator. this is ambiguous matches. Add the anchors so your step will be unique to each others.
2. Step Parameter
Given("^the client adds (\\d+) \"(.*)\" product into Cart$", (Integer addOnQuantity, String addOnName)
example step name: "Given the client adds 6 "IphoneX" product into Cart"
\d+ means one or more digits. we have two parameters here (2 capture groups), one is the quantity of the product(Integer) and the other is the name of product (String).
3. Capture and non-Capture Group
When you put part of a regular expression in parentheses, whatever it matches gets captured for use later. This is known as a “capture group.” In Cucumber, captured strings become step definition parameters. Typically, if you’re using a wildcard, you probably want to capture the matching value for use in your step definition.
Back to the example in the item 2:
Given("^the client adds (\\d+) \"(.*)\" product into Cart$", (Integer addOnQuantity, String addOnName) -> {}
We have 2 capture groups here. (\d+) and (.*)
Sometimes, you have to use parentheses to get a regular expression to work, but you don’t want to capture the match. For example, suppose I want to be able to match both “the client logged in” and “the admin logged in”. We can write like this:
Given("^the (?:client|admin) logged in$", () -> {}
with the addition of ?: at the beginning of the group, it will treat the first group as non-capturing.
I think I only use these above regular expression syntax to write all my cucumber tests.
If you want to learn more about regular expression, read this.
Reference Links:
https://agileforall.com/just-enough-regular-expressions-for-cucumber/