Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 37 ยท Step Definitions

Regular Expression Step Patterns

Use regular expressions in Cucumber step definitions: how Cucumber decides between regex and Cucumber expressions, capture groups, anchors, greedy pitfalls and optional groups.

Before Cucumber expressions existed, every step definition was a regular expression, and regexes are still fully supported. They are the escape hatch for sentences that Cucumber expressions cannot describe. This lesson explains when to reach for one, how capture groups become method arguments, and the handful of traps that cause most regex-related bugs.

How Cucumber chooses

Cucumber-JVM treats the annotation string as a regular expression if it starts with ^ or ends with $, or if it is not a valid Cucumber expression. Otherwise it is a Cucumber expression. That means a leading caret is a reliable switch:

Java
@Then("^the cart total is (\\d+) dollars$")      // regular expression
@Then("the cart total is {int} dollars")         // Cucumber expression

Each capturing group ( ... ) becomes one method argument, in order. Cucumber converts the text to the parameter's Java type: int, long, double, String, BigDecimal, enums and so on.

Basic patterns

Regex Matches Typical use
(\d+) digits counts, ids
(\d+\.\d{2}) 19.99 money with two decimals
"([^"]*)" text between double quotes, quotes excluded strings with spaces
(\w+) letters, digits, underscore single-word values
(open|closed) exactly one of the words a small closed set
(?:a|an) non-capturing group grammar variations that must not become arguments
(?:\s+and\s+(\d+))? optional section variable-length sentences

Since Cucumber expressions already provide , and , switch to regex only when you need:

  • Complex optional structure, for example a sentence that may or may not end with "and the receipt is emailed".
  • Matching a whole class of sentences with one definition (^(?:the )?customer (?:signs in|logs in)$).
  • A format unknown to the built-in types where defining a parameter type would be overkill.

Anchors: always use them

Cucumber's regular expression matcher succeeds when the pattern matches the beginning of the sentence, not necessarily all of it. A definition the cart total is (\d+) would therefore accept the cart total is 36 dollars and more text and silently ignore the rest. Wrap every regex step in ^ and $:

Java
@Then("^the cart total is (\\d+) dollars$")

The stand-in below shows the difference between prefix matching (lookingAt) and a full match, so the danger is visible. Run it and see which sentences the unanchored pattern wrongly accepts.

Java Stand-in: anchored versus unanchored patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Greedy and lazy groups

The biggest source of bugs is (.*): it is greedy, consuming as much as it can. Given the sentence the user "ann" and "bob" are friends, the pattern ^the user "(.*)" and "(.*)" are friends$ works, but ^the user "(.*)" finds one group ann" and "bob. Safer options:

  • "([^"]*)": anything except a quote, which stops at the first closing quote.
  • (.+?): lazy, taking as little as possible.
  • A tighter character class such as (\w+).
Java Stand-in: greedy, lazy and negated groups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The greedy group runs to the last quote in the sentence and captures ann" and "bob as one value. The lazy and negated groups stop at the first closing quote.

Optional groups

An optional capture group that did not take part in the match yields null for that argument. In Java, primitive int cannot hold null, which causes an error; use the wrapper Integer or String:

Java
@When("^the customer adds (\\d+) books?(?: with a (\\d+) percent coupon)?$")
public void adds(int count, Integer couponPercent) {
    int percent = (couponPercent == null) ? 0 : couponPercent;
    ...
}

Both sentences match this single definition:

GHERKIN
When the customer adds 2 books
When the customer adds 3 books with a 10 percent coupon

Optional groups save definitions but cost clarity. If a sentence has more than one optional part, consider two definitions or a parameter type instead.

Converting a regex definition into code: a stand-in

The stand-in below mimics how the real engine maps groups to typed parameters, including null for an unmatched optional group. It converts each group according to a declared type string, so you can see why Integer (not int) is needed for optional parts.

Java Stand-in: groups to typed arguments, nulls included

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Practical advice

  1. Default to Cucumber expressions. They produce friendlier messages and snippets, and teammates read them faster.
  2. Always anchor regexes with ^ and $.
  3. Prefer negated character classes ([^"]*) over .*.
  4. Use non-capturing groups (?:...) for wording that should not become an argument; unexpected extra groups shift every later parameter.
  5. Escape Java strings twice: \d is "\\d" in source code; use a raw approach like a constant if the pattern gets long.
  6. Test the regex first in a scratch program, as the stand-ins above do, before committing it.

Often the best fix for a messy regex is a custom parameter type. That is the subject of the next lesson: parameter types.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does Cucumber-JVM decide that an annotation string is a regular expression?

    A leading caret or trailing dollar is the reliable way to select regex mode.
  2. 2. Why should regex steps be anchored with ^ and $?

    Unanchored patterns can silently accept longer, different sentences, so anchors make the intent explicit.
  3. 3. What does an optional capture group that did not match pass to the method?

    Use a wrapper type such as Integer, because primitive int cannot hold null.
  4. 4. Which pattern safely captures text between double quotes?

    A negated character class cannot run past the closing quote the way greedy .* can.

Summary

  • A step string beginning with ^ or ending with $ is a regular expression; each capturing group becomes an argument.
  • Always anchor and prefer negated character classes over greedy (.*).
  • Use non-capturing groups for wording that should not be an argument.
  • Unmatched optional groups arrive as null; use wrapper types.
  • Default to Cucumber expressions and use regex only for what they cannot express.

Next: Custom Parameter Types