Regular Expressions in Steps
Instead of {placeholder} tokens, a step pattern can be a full Python regular expression. This gives precise control over which steps match: you can restrict a value to digits, a date format, or an email-like shape directly in the pattern. Write the pattern as a raw string so the backslashes survive.
Named Groups as Arguments
Named groups in the pattern are passed to the step function as keyword arguments, in the same way placeholders are passed.
from behave import step
@step(r"I have (?P<num>\d+) cucumbers in my belly")
def step_impl(context, num):
context.cucumbers = int(num)
Positional Groups
Groups without a name are passed as positional arguments, in the order they appear in the pattern:
Given an order for 3 items at 12.50 each
from behave import step
@step(r"an order for (\d+) items at ([\d.]+) each")
def step_impl(context, qty, unit_price):
context.order_total = int(qty) * float(unit_price)
Enforcing Formats
The main advantage of a regex step is that an impossible value simply never matches, so it is reported as an unmatched step instead of crashing later:
from behave import step
@step(r"the client at (?P<ip>\d{1,3}(?:\.\d{1,3}){3}) connects")
def step_impl(context, ip):
context.client_ip = ip
When to Prefer Which
Use plain placeholders for everyday steps; they read better in the feature file and keep the step module simple. Reach for regular expressions when the step text itself carries a format you want to enforce, or when one step must match several alternative shapes that placeholders cannot express.
Summary
Regex step patterns replace placeholders with real regular expressions. Named groups map to keyword arguments, unnamed groups to positional ones, and all captured values still arrive as strings that you convert explicitly.