Skip to main content

Cucumber Optional Non-Capturing Groups

Consider a case when multiple sentences has the same meaning. In that case we do not create separate Step Definition. There is a way to achieve this in Cucumber.

The addition of ?: to the beginning of Optional Capture groups creates optional non-Capture groups. Having ?: will treat the group as optional.

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

In Optional Capture group we have different conditions for positive and negative cases that's why we have to received values as argument but in case of Optional Non-Capture there is no need to receive values in arguments.

Cucumber Optional Parameter

Check in below feature file how 4 different user following the same link

 #Example of Non-Optional Capture Group
  @smoke @nonoptional
  Scenario: Keyword Search
    When I fill "search textbox" with "dress"
    Then I click "search button"
    Then I follow "TOP SELLERS" link
    Then She follow "TOP SELLERS" link
    Then He follow "TOP SELLERS" link
    Then User follow "TOP SELLERS" link

Java RegEx Non Capturing Group

In that case we need single Step Definition 

@Then("^(?:I|She|He|User) follow \"([^\"]*)\" link$")
  public void i_follow_on_page(String link) 

In above example you can see we are not receiving value of I, She, He, User in method argument. 

Submitted by tgoswami on August 30, 2020

Tarun has 11+ years of experience in Quality Assurance in different domains like Banking, E-commerce, Health and Education.


At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.