Search code examples
javaregexcucumbercucumber-jvm

Cucumber arity mismatch: trying to bind several matching groups to a single stepdef parameter


I'm trying to create a regular expression that will match the following:

Given I'm a user
Given I am a user
Given Dylan is a user

And this is my step definition:

@Given("^(?:(I)'m|(I) am|(.+) is) a user$")
public void aUserExists(String username) throws Throwable {
}

It's matching what I need, but seems like Cucumber is trying to assign each capturing group in the non-capturing group to a parameter, while I want it to assign just one:

cucumber.runtime.CucumberException: Arity mismatch: Step Definition 'hello.MyStepdefs.aUserExists(String) in [...] with pattern [^(?:(I)'m|(I) am|(.+) is) a user$] is declared with 1 parameters. However, the gherkin step has 3 arguments [I, null, null].

I'm coming from PHP background and this regular expression worked great with Behat. Maybe I'm not getting something about Java regular expressions or Cucumber behavior.


Update

Since all the current answers are having the same problem, I'm updating the question.

I don't want to match a string like:

Given I is a user

I want to match I only when it's followed by 'm or am. I hope it's not an impossible thing to do with Java regular expressions and Cucumber.


Solution

  • I am not sure if that is what you are looking for but if you want to capture user name in group one without creating more groups then maybe try

    "^(\\w+)(?:(?<=I\\b)(?:'m| am)|(?<!^I\\b) is) a user$"