Question

When asked, IntelliJ automatically creates a ruby step for this Gherkin from a .feature file

And I "foo" bar

as this in a .rb file

When /^I "([^"]*)" bar$/ do |arg|
  pending
end

I'm puzzled as to [^"]* instead of .*

I also had a coworker mention that I should use .*? instead of either of the above. I challenged him to provide a concrete example of a set of Gherkin strings that would be parsed differently between any of the following ruby steps.

Where one ruby step uses

When /^I "([^"]*)" bar$/ do |arg|
  pending
end

Another uses

When /^I "(.*)" bar$/ do |arg|
  pending
end

And another uses

When /^I "(.*?)" bar$/ do |arg|
  pending
end

but he never got back to me with one that made a difference between any of the three. I assume he never found a good example.

I think that .* is the simplest of all three regular expressions, and I'd like to use that predominately in my ruby step definitions. Can someone provide concrete examples of where either one of the other two steps is distinctly advantageous from a correctness standpoint? I don't care about regex parse time.

Was it helpful?

Solution

.* will lead to errors for strings like This is a "test" string with multiple " in place". ".*" would match the substring "test" string with multiple " in place" while "[^"]*" and ".*?" would only match "test". This is because * is a greedy quantifier which will try to match as many characters as possible.

Whether to use [^"]* or .*?: Doesn't really matter in terms of correctness.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top