Cucumber Optional Non-Capturing Groups

Profile picture for user devraj

Example: Using Optional Non-Capturing Group

Consider a case when multiple sentences have the same meaning. 

Then She follows the "TOP SELLERS" link
Then He follows the "TOP SELLERS" link
Then User follows the "TOP SELLERS" link
Then I follow the "TOP SELLERS" link

In the above case, there is no need to create four-step definitions. All steps can be handled using a single-step definition. Also, we only want to capture the value of TOP SELLERS.

She, He, User, and I are values we do not want to capture and do not want to store in variable received as a method parameter. In that case, we can use ?: in our capture group. Adding ?: to the beginning of Optional Capture groups creates optional non-Capturing groups. Having ?: will treat the group as optional.

@Then("^(?:She|He|User|I) follow(?:|s) the \"([\\w\\s]+)\" link$")
public void she_follows_the_link(String string) {
}

Here using follows with I is grammatically incorrect, so we can also make s optional by using a non-capturing group. Notice ?: and | symbol just after follow.

You can use an optional non-capturing group to retain the grouping benefits but without the overhead of capturing. So, you do not need to pass an argument described earlier with optional captured groups.

Example: Capture Digit From String

Consider another case where you want to match a sequence of digits followed by one of the prefixes -st-nd-rd-th (e.g., 1st4th). Here you only want to capture 1, 2, 3, or 4 values to store them in variable, not -st, -nd, -rd, or -th value.

Then I select 1st value
Then I select 2nd value
Then I select 3rd value
Then I select 4th value
@Then("^I select ([0-9]+)(?:st|nd|rd|th) value$")
public void i_select_1st_value(int a) {
}

Video Tutorial: Cucumber Non Capturing Group