← Back to libraryQuestion 258 of 468
🥒Cucumber / BDDIntermediate

Cucumber Expressions vs Regular Expressions

📌 Definition:

Step patterns can be written as Cucumber Expressions (readable placeholders like {int}, {string}, {word}) or as regular expressions. Cucumber Expressions are simpler and preferred for most cases.

📖 Detailed Explanation:

A Cucumber Expression such as @When("the user adds {int} items") captures an integer parameter cleanly, with built-in types {int}, {float}, {word}, {string} (quoted), and support for custom parameter types (e.g. {color} mapped to an enum). Regex (@When("^the user adds (\\d+) items$")) is more powerful for complex matching but harder to read. You cannot mix both in one expression. Custom parameter types let you convert captured text into domain objects (a Date, a User), keeping step definitions clean. Choosing Cucumber Expressions by default improves readability; drop to regex only when you need advanced matching.

🔑 Key Points:
  • Cucumber Expressions: {int}, {float}, {word}, {string} — readable
  • Regex is more powerful but less readable (can't mix the two)
  • Custom parameter types convert text → domain objects
  • Prefer Cucumber Expressions; use regex only when needed
🌍 Real-World Example:

@When("the user selects the {string} plan") captures a quoted plan name; a custom {plan} type could convert 'premium' directly into a Plan enum for the step method.

🎯 Scenario-Based Interview Question:

Write a step pattern that captures a quantity and a product name from: 'the user buys 3 apples'. Which expression type is cleaner?