Pattern Match
The Pattern Match metric measures whether your LLM application's actual_output matches a given regular expression pattern. This is useful for testing your model's ability to produce outputs in a specific format, structure, or syntax.
Required Arguments
To use the PatternMatchMetric, you'll have to provide the following arguments when creating an LLMTestCase:
input-
actual_output
Read the How Is It Calculated section below to learn how test case parameters are used for metric calculation.
Usage
from deepeval.metrics import PatternMatchMetric
from deepeval.test_case import LLMTestCase
from deepeval import evaluate
# Pattern: expects a valid email format
metric = PatternMatchMetric(
pattern=r"^[\w\.-]+@[\w\.-]+\.\w+$",
ignore_case=False,
threshold=1.0,
verbose_mode=True
)
test_case = LLMTestCase(
input="Generate a valid email address.",
actual_output="example.user@domain.com"
)
# To run metric as a standalone
# metric.measure(test_case)
# print(metric.score, metric.reason)
evaluate(test_cases=[test_case], metrics=[metric])There is ONE mandatory and FOUR optional parameters when creating a PatternMatchMetric:
pattern: a string representing the regular expression pattern that theactual_outputmust match.- [Optional]
ignore_case: a boolean which when set toTrue, performs case-sensitive pattern matching. Defaulted toFalse. - [Optional]
threshold: a number representing the minimum passing threshold. Can also be set toNoneto run the metric in score-only mode. Defaulted to1.0. - [Optional]
verbose_mode: a boolean which when set toTrue, prints the intermediate steps used to calculate said metric to the console, as outlined in the How Is It Calculated section. Defaulted toFalse. - [Optional]
flaky: a boolean which when set toTrue, marks the metric as flaky. Defaulted toFalse.
As a Standalone
You can also run the PatternMatchMetric on a single test case as a standalone, one-off execution.
...
metric.measure(test_case)
print(metric.score, metric.reason)How Is It Calculated?
The PatternMatchMetric score is calculated according to the following equation:
The match is determined using Python's built-in regular expression engine re.fullmatch, which ensures the actual_output matches the provided pattern.
FAQs
Why does my pattern fail when it clearly matches part of the output?
re.fullmatch, so the pattern must match the entire actual_output, not a substring. \d+ fails on "The code is 1234"; wrap with .* (e.g. .*\d+.*) to match a fragment.Does the Pattern Match metric call an LLM or cost money?
PatternMatchMetric uses pure regex matching — no model, no API key, zero token cost, fully deterministic.Can I make the pattern matching case-insensitive?
ignore_case=True to ignore casing when matching actual_output against the pattern. Defaults to False.