pytest-dev/pytest · error · UsageError
Invalid regex
Error message
Invalid regex {e.pattern!r}: {e} What it means
Raised by parse_warning_filter() when the message or module field of a warning filter is not a valid regular expression. After parsing the fields, pytest compiles both the message and module patterns with re.compile(); if either fails, a re.error is caught and re-raised as UsageError with the pattern and error.
Solutions
- Fix the regex syntax in the message or module field
- For config-provided filters, pytest auto-escapes the message and module (escape=True), so literal special chars are usually safe
- For CLI -W flags, escape regex metacharacters manually or simplify to a plain substring
Example fix
# before (CLI flag, not auto-escaped) pytest -W "ignore:(unbalanced:DeprecationWarning" # after pytest -W "ignore:\(balanced\):DeprecationWarning"
Defensive patterns
Strategy: validation
Validate before calling
import re
def validate_warning_filter_regex(arg: str) -> bool:
parts = arg.split(':')
# Pad to 5 fields
while len(parts) < 5:
parts.append('')
message, module = parts[1], parts[3]
try:
re.compile(message)
re.compile(module)
return True
except re.error:
return False Try / catch
from pytest import UsageError
try:
parse_warning_filter(arg, escape=True)
except UsageError as e:
print(f"Invalid regex in filter: {e}") Prevention
- For config-provided filters, pytest auto-escapes message/module so literal text is safe
- For CLI -W flags, escape regex metacharacters or use simple substrings
- Test regex patterns with re.compile before adding to config
When it happens
Trigger: Providing a warning filter where the message or module segment contains an invalid regex. Example: filterwarnings = ["ignore:'(::DeprecationWarning"] — the message pattern has an unbalanced parenthesis. When escape=True (the default for config-provided filters), special chars are escaped, but raw CLI flags (-W) are not escaped.
Common situations: Using unescaped special regex characters in a CLI -W flag's message or module field. Malformed regex from a typo. Copying a filter string that was intended for a different regex engine.
Related errors
- is not a Warning subclass
- invalid lineno
- Too many fields ( ), expected at most 5 separated by…
- alias conflicts with existing configuration option
- is already an alias of
AI-assisted analysis of pytest-dev/pytest@0d6fbdeffa (2026-08-11).
Data as JSON: /api/errors/fc62040c9ce5398a.
Report an issue: GitHub.
Appendix: source
Thrown at src/_pytest/config/__init__.py:2320
message = re.escape(message)
if module and escape:
module = re.escape(module) + r"\Z"
if lineno_:
try:
lineno = int(lineno_)
if lineno < 0:
raise ValueError("number is negative")
except ValueError as e:
raise UsageError(
error_template.format(error=f"invalid lineno {lineno_!r}: {e}")
) from None
else:
lineno = 0
try:
re.compile(message)
re.compile(module)
except re.error as e:
raise UsageError(
error_template.format(error=f"Invalid regex {e.pattern!r}: {e}")
) from None
return action, message, category, module, lineno
def _resolve_warning_category(category: str) -> type[Warning]:
"""
Copied from warnings._getcategory, but changed so it lets exceptions (specially ImportErrors)
propagate so we can get access to their tracebacks (#9218).
"""
__tracebackhide__ = True
if not category:
return Warning
if "." not in category:
import builtins as m
klass = categoryView on GitHub (pinned to 0d6fbdeffa)