Search code examples
regexcucumbercucumber-jvm

How to use non-capturing parenthesis to capture a word or nothing at all?


I am looking to use two variations of the same step in my ATDD test using cucumber-jvm

Then order passes quantity limits

and

Then order passes limits

This will read better with different scenarios. I have tried various variations of the following:

@Then(value = "^order passes (?: | quantity )limits$")
public void verifyCreditPassed(){ 
    //Assert stuff
}

Can anyone help?

Thanks


Solution

  • You need to remove the ^ and $ meta-characters then you regex becomes:

    order passes (?:quantity |)limits
    

    because when you use ^ the line must start with the word order and because you used $ the line must end with limits, the above regex will match your sentence anywhere inside the input string.

    or use the following regex:

    ^Then order passes (?:quantity )?limits$