Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 37 ยท Step Definitions

Cucumber Expressions: {int}, {string}, Optionals and Alternatives

Master Cucumber expressions: built-in parameter types such as int, float, word and string, optional text, alternation, escaping, and how they compile to regular expressions.

Cucumber expressions are the default way to write step patterns. They look like the sentence they match, with a few special marks, so a step definition reads almost like the line in the feature file. They are less powerful than regular expressions but far easier to read, and for nearly every step they are the right choice.

The building blocks

Syntax Meaning Example
Plain text Matches itself exactly the cart is empty
An integer, passed as int adds {int} books
/ A decimal number costs {float} dollars
One word without whitespace the {word} plan
Text in single or double quotes, quotes removed user {string} signs in
{} (anonymous) Anything, as a string the message is {}
(text) Optional text book(s)
a/b Alternative the customer adds/removes {int} book(s)
\ Escapes a special character costs \$5

Built-in parameter types

Cucumber ships with these types. Each has a regular expression to find the text and a conversion to the Java type.

Type Java type Example text
int 42, -7
, , byte, short, long 1000
BigInteger 123456789012345678901
, float, double 3.14, -0.5
BigDecimal 19.99
String gold
String "Maria Lopez"
{} String or any object anything

Use for money: floats cannot represent most decimal fractions exactly.

Java
@When("the customer pays {bigdecimal} dollars")
public void theCustomerPays(BigDecimal amount) { ... }

{string}: quotes included, quotes removed

matches text surrounded by double or single quotes and passes the text without the quotes. That lets the sentence carry values with spaces:

GHERKIN
When the user "Maria Lopez" signs in with the password 'p@ss word'
Java
@When("the user {string} signs in with the password {string}")
public void signIn(String user, String password) { ... }

Optional text and alternatives

Parentheses make adjacent text optional. book(s) matches both "book" and "books", which is perfect for singular and plural without writing two definitions:

Java
@When("the customer adds {int} book(s)")

A slash gives alternatives. There must be no spaces around it, and the alternatives are the words directly next to the slash:

Java
@Then("the account is open/closed")              // matches "open" or "closed"
@When("the customer adds/removes {int} book(s)") // four combinations

Alternatives cannot contain parameters or optionals, so if a variation is more complex, write two definitions or use a parameter type (next lessons).

Escaping

The characters (, ), {, }, / and \ are special. To match them literally, put a backslash in front. In Java string literals the backslash itself must be doubled:

Java
@Then("the price is \\(about\\) {int} dollars")   // matches: the price is (about) 5 dollars
@Then("the ratio is {int}\\/{int}")               // matches: the ratio is 3/4

How expressions work: translation to regular expressions

Internally, Cucumber translates a Cucumber expression into a regular expression, replacing each with a group built from that type's regex, then converting the captured text with the type's transformer. Understanding this explains most surprises. The stand-in below implements the idea for , , , , optionals and alternatives, and prints the regular expression it builds for each expression. It is a teaching model, not the real library (which has a proper parser with better error messages).

Java Stand-in: compile Cucumber expressions to regex

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 last case shows a useful fact: does not accept 12.5. The sentence simply does not match, and Cucumber reports it undefined, usually with a snippet using .

Choosing the right parameter type

  • Counts and ids: or .
  • Money: .
  • Free text with spaces (names, messages): with quotes in the feature file.
  • A single token (plan names, statuses): . It cannot contain spaces.
  • Dates, enums, domain objects: define a custom parameter type, which keeps step methods free of parsing code.

Avoid the anonymous {} except for quick experiments: it matches anything, so it is a frequent cause of ambiguous steps.

Tips for readable expressions

  1. Write the sentence first, then add parameters. If the expression is hard to read, the sentence probably is too.
  2. One variation point per definition. Several alternations and optionals in one expression produce a sentence nobody can search for.
  3. Search-friendly. IDEs can jump from a sentence to its definition; plain text and few alternations help them.
  4. Quote strings in features so can tell where a value starts and ends.
  5. Prefer a parameter type over a method that parses text.

When an expression can't express what you need (for example conditional structure or lookahead), switch to a regular expression, as covered next: regex step patterns.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which expression matches both 'adds 1 book' and 'adds 3 books'?

    Parentheses make the 's' optional, so one definition handles singular and plural.
  2. 2. What does {string} pass to the method for the text "Maria Lopez" (with quotes in the feature file)?

    The quotes delimit the value but are removed before the argument is passed.
  3. 3. Which type is best for money amounts?

    BigDecimal avoids the rounding errors binary floating point has with decimal fractions.
  4. 4. How do you match a literal slash in a Cucumber expression written in a Java string?

    The expression needs a backslash before the slash; in a Java string literal the backslash is written twice.
  5. 5. Why is the anonymous {} parameter risky?

    Because it matches any text, it can overlap with other definitions.

Summary

  • Cucumber expressions are readable patterns: plain text, parameters, (optional) text and a/b alternatives.
  • Built-in types include int, long, float, double, bigdecimal, word, string and the anonymous {}.
  • expects quotes and strips them; matches one token.
  • Expressions compile to regular expressions; if a sentence does not fit a type, it simply does not match.
  • Use custom parameter types and regular expressions when the built-ins are not enough.

Next: Regular Expression Step Patterns