0
# Cucumber Expressions
1
2
Cucumber Expressions is a multi-language library providing a simpler alternative to Regular Expressions for matching step definitions with Gherkin steps in Behavior-Driven Development (BDD) testing. It offers an intuitive syntax using parameter types like `{int}`, `{float}`, `{string}`, and `{word}`, supports optional text with parentheses and alternative text with forward slashes, and includes advanced features like custom parameter types and expression generation.
3
4
## Package Information
5
6
- **Package Name**: cucumber-expressions
7
- **Package Type**: Multi-language (JavaScript/TypeScript, Python, Java, Ruby, Go, .NET)
8
- **Version**: 18.0.1
9
- **Repository**: https://github.com/cucumber/cucumber-expressions
10
11
### Installation
12
13
**JavaScript/TypeScript (npm):**
14
```bash
15
npm install @cucumber/cucumber-expressions
16
```
17
18
**Python (PyPI):**
19
```bash
20
pip install cucumber-expressions
21
```
22
23
**Java (Maven):**
24
```xml
25
<dependency>
26
<groupId>io.cucumber</groupId>
27
<artifactId>cucumber-expressions</artifactId>
28
<version>18.0.1</version>
29
</dependency>
30
```
31
32
**Ruby (Gem):**
33
```bash
34
gem install cucumber-cucumber-expressions
35
```
36
37
**Go (Module):**
38
```bash
39
go get github.com/cucumber/cucumber-expressions/go/v18
40
```
41
42
**.NET (NuGet):**
43
```bash
44
dotnet add package Cucumber.CucumberExpressions
45
```
46
47
## Core Imports
48
49
**JavaScript/TypeScript:**
50
```typescript
51
import { CucumberExpression, ParameterTypeRegistry, ExpressionFactory } from '@cucumber/cucumber-expressions';
52
```
53
54
**Python:**
55
```python
56
from cucumber_expressions import CucumberExpression, ParameterTypeRegistry, CucumberExpressionGenerator
57
```
58
59
**Java:**
60
```java
61
import io.cucumber.cucumberexpressions.CucumberExpression;
62
import io.cucumber.cucumberexpressions.ParameterTypeRegistry;
63
import io.cucumber.cucumberexpressions.ExpressionFactory;
64
```
65
66
## Basic Usage
67
68
```typescript
69
import { CucumberExpression, ParameterTypeRegistry } from '@cucumber/cucumber-expressions';
70
71
// Create parameter type registry with built-in types
72
const registry = new ParameterTypeRegistry();
73
74
// Create a Cucumber Expression
75
const expression = new CucumberExpression('I have {int} cucumber(s) in my belly', registry);
76
77
// Match text against the expression
78
const args = expression.match('I have 42 cucumbers in my belly');
79
if (args) {
80
console.log(args[0].getValue()); // 42 (as number)
81
}
82
83
// Expression with different parameter types
84
const floatExpr = new CucumberExpression('I have {float} cucumbers in my belly', registry);
85
const floatArgs = floatExpr.match('I have 42.5 cucumbers in my belly');
86
if (floatArgs) {
87
console.log(floatArgs[0].getValue()); // 42.5 (as number)
88
}
89
```
90
91
## Architecture
92
93
Cucumber Expressions is built around several key components:
94
95
- **Expression Parser**: Parses Cucumber expressions into Abstract Syntax Trees (AST) for matching
96
- **Parameter Type System**: Built-in and custom parameter types with regex patterns and transformers
97
- **Registry Pattern**: Central parameter type registry for managing type definitions
98
- **Factory Pattern**: Expression factory for creating expressions from strings or regex patterns
99
- **Expression Generator**: Generates expressions from example text for step definition creation
100
- **Multi-language Consistency**: Consistent APIs across all supported programming languages
101
102
The library uses a grammar-based parser to convert expressions like `I have {int} cucumber(s)` into regular expressions with appropriate capture groups, enabling type-safe parameter extraction.
103
104
## Core Parameter Types
105
106
All implementations support these built-in parameter types:
107
108
| Parameter Type | Description | Example Match | Converted Type |
109
|----------------|-------------|---------------|----------------|
110
| `{int}` | 32-bit signed integers | `42`, `-19` | Integer |
111
| `{float}` | 32-bit floating point | `3.6`, `.8`, `-9.2` | Float |
112
| `{word}` | Single word (no whitespace) | `banana` | String |
113
| `{string}` | Quoted strings | `"banana split"`, `'hello'` | String (without quotes) |
114
| `{bigdecimal}` | High-precision decimals | `123.456789` | BigDecimal/Decimal |
115
| `{double}` | 64-bit floating point | `3.14159` | Double |
116
| `{biginteger}` | Arbitrary precision integers | `12345678901234567890` | BigInteger |
117
| `{byte}` | 8-bit signed integer | `127`, `-128` | Byte |
118
| `{short}` | 16-bit signed integer | `32767` | Short |
119
| `{long}` | 64-bit signed integer | `9223372036854775807` | Long |
120
| `{}` (anonymous) | Matches anything | `anything` | String (varies by language) |
121
122
## Capabilities
123
124
### Expression Parsing and Matching
125
126
Core functionality for parsing Cucumber expressions and matching them against text, with support for parameter extraction and type conversion.
127
128
```typescript { .api }
129
class CucumberExpression implements Expression {
130
constructor(expression: string, parameterTypeRegistry: ParameterTypeRegistry);
131
match(text: string): readonly Argument[] | null;
132
readonly source: string;
133
readonly regexp: RegExp;
134
readonly ast: Node;
135
}
136
137
interface Expression {
138
readonly source: string;
139
match(text: string): readonly Argument[] | null;
140
}
141
```
142
143
[JavaScript/TypeScript Implementation](./javascript-typescript.md)
144
145
### Parameter Type System
146
147
Comprehensive parameter type system with built-in types and support for custom parameter types with regex patterns and transformation functions.
148
149
```typescript { .api }
150
class ParameterType<T> {
151
constructor(
152
name: string | undefined,
153
regexps: RegExps,
154
type: Constructor<T> | Factory<T> | null,
155
transform?: (...match: string[]) => T | PromiseLike<T>,
156
useForSnippets?: boolean,
157
preferForRegexpMatch?: boolean
158
);
159
160
readonly name: string | undefined;
161
readonly regexpStrings: readonly string[];
162
transform(thisObj: unknown, groupValues: string[] | null): T;
163
}
164
165
class ParameterTypeRegistry implements DefinesParameterType {
166
constructor();
167
defineParameterType(parameterType: ParameterType<unknown>): void;
168
lookupByTypeName(typeName: string): ParameterType<unknown> | undefined;
169
lookupByRegexp(parameterTypeRegexp: string, expressionRegexp: RegExp, text: string): ParameterType<unknown> | undefined;
170
}
171
```
172
173
[Parameter Types](./parameter-types.md)
174
175
### Expression Factory and Generation
176
177
Factory pattern for creating expressions and generator for creating expressions from example text, useful for step definition creation.
178
179
```typescript { .api }
180
class ExpressionFactory {
181
constructor(parameterTypeRegistry: ParameterTypeRegistry);
182
createExpression(expression: string | RegExp): Expression;
183
}
184
185
class CucumberExpressionGenerator {
186
constructor(parameterTypes: () => Iterable<ParameterType<unknown>>);
187
generateExpressions(text: string): readonly GeneratedExpression[];
188
}
189
190
class GeneratedExpression {
191
constructor(expressionTemplate: string, parameterTypes: readonly ParameterType<unknown>[]);
192
readonly source: string;
193
readonly parameterNames: readonly string[];
194
readonly parameterInfos: readonly ParameterInfo[];
195
}
196
```
197
198
[Expression Factory and Generation](./expression-factory.md)
199
200
### Python Implementation
201
202
Complete Python implementation with Pythonic API patterns, built-in parameter types, and full feature compatibility.
203
204
```python { .api }
205
class CucumberExpression:
206
def __init__(self, expression: str, parameter_type_registry: ParameterTypeRegistry): ...
207
def match(self, text: str) -> Optional[List[Argument]]: ...
208
209
@property
210
def source(self) -> str: ...
211
212
class ParameterType:
213
def __init__(
214
self,
215
name: Optional[str],
216
regexp: Union[List[str], str, List[Pattern], Pattern],
217
type: type,
218
transformer: Optional[Callable] = None,
219
use_for_snippets: bool = True,
220
prefer_for_regexp_match: bool = False
221
): ...
222
```
223
224
[Python Implementation](./python.md)
225
226
### Java Implementation
227
228
Enterprise-grade Java implementation with strong typing, comprehensive built-in types, and extensive configuration options.
229
230
```java { .api }
231
public final class CucumberExpression implements Expression {
232
public CucumberExpression(String expression, ParameterTypeRegistry parameterTypeRegistry);
233
public List<Argument<?>> match(String text, Type... typeHints);
234
public String getSource();
235
public Pattern getRegexp();
236
}
237
238
public final class ParameterType<T> implements Comparable<ParameterType<?>> {
239
public ParameterType(String name, List<String> regexps, Class<T> type, CaptureGroupTransformer<T> transformer);
240
public T transform(List<String> groupValues);
241
public String getName();
242
public List<String> getRegexps();
243
}
244
```
245
246
[Java Implementation](./java.md)
247
248
### Additional Language Implementations
249
250
Support for Ruby, Go, and .NET implementations with language-specific patterns and conventions while maintaining API compatibility.
251
252
[Ruby Implementation](./ruby.md)
253
[Go Implementation](./go.md)
254
[.NET Implementation](./dotnet.md)
255
256
## Types
257
258
```typescript { .api }
259
interface Argument {
260
readonly group: Group;
261
readonly parameterType: ParameterType<unknown>;
262
getValue<T>(thisObj: unknown): T | null;
263
getParameterType(): ParameterType<unknown>;
264
}
265
266
interface GeneratedExpression {
267
readonly source: string;
268
readonly parameterNames: readonly string[];
269
readonly parameterInfos: readonly ParameterInfo[];
270
readonly parameterTypes: readonly ParameterType<unknown>[];
271
}
272
273
interface ParameterInfo {
274
type: string | null;
275
name: string;
276
count: number;
277
}
278
279
interface Group {
280
value: string | null;
281
start: number;
282
end: number;
283
children: Group[];
284
}
285
286
interface Node {
287
type: NodeType;
288
nodes?: Node[];
289
token?: Token;
290
text(): string;
291
}
292
293
enum NodeType {
294
text = 'text',
295
optional = 'optional',
296
alternation = 'alternation',
297
alternative = 'alternative',
298
parameter = 'parameter',
299
expression = 'expression'
300
}
301
```
302
303
## Expression Syntax
304
305
Cucumber Expressions support several powerful syntax features:
306
307
### Parameter Types
308
Use curly braces to define typed parameters:
309
- `I have {int} cucumbers` - matches integers
310
- `I have {float} cucumbers` - matches floating point numbers
311
- `I have {string} cucumbers` - matches quoted strings
312
- `I have {word} cucumbers` - matches single words
313
314
### Optional Text
315
Use parentheses for optional text:
316
- `I have {int} cucumber(s)` - matches both "cucumber" and "cucumbers"
317
318
### Alternative Text
319
Use forward slashes for alternatives:
320
- `I have {int} cucumber(s) in my belly/stomach` - matches either "belly" or "stomach"
321
322
### Escaping
323
Escape special characters with backslashes:
324
- `I have {int} \\{what} cucumber(s)` - matches literal `{what}`
325
- `I have {int} cucumber(s) \\(amazing!)` - matches literal `(amazing!)`
326
327
### Anonymous Parameters
328
Use empty braces for catch-all matching:
329
- `I have {} cucumbers` - matches any text