pytest-dev/pytest · error · UsageError
Invalid regex {e.pattern!r}: {e}
Error message
Invalid regex {e.pattern!r}: {e} What it means
Pytest raises this UsageError when the message or module field of a warning filter specification is not a valid regular expression. Pytest compiles both fields with re.compile() after optional escaping; a re.error indicates the regex syntax is broken.
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 98b357f69e)
Solutions
- Escape regex metacharacters in your message pattern, or test it with python -c 'import re; re.compile("your pattern")'.
- Use plain substring text (no metacharacters) for simple matches.
- If you need a literal special character, prefix with backslash (e.g. '\(' to match a literal paren).
Example fix
# before (unbalanced bracket) [pytest] filterwarnings = ["ignore:[unbalanced:DeprecationWarning"] # after [pytest] filterwarnings = ["ignore:\[unbalanced:DeprecationWarning"]
Defensive patterns
Strategy: validation
Validate before calling
import re
def validate_filter_regex(message: str, module: str) -> None:
for label, pattern in (('message', message), ('module', module)):
if pattern:
try:
re.compile(pattern)
except re.error as e:
raise ValueError(f'Invalid {label} regex {pattern!r}: {e}') from None Type guard
import re
def is_valid_regex(pattern: str) -> bool:
try:
re.compile(pattern)
return True
except re.error:
return False Try / catch
import re
try:
re.compile(user_message)
except re.error as e:
print(f'message field is not valid regex: {e}'); user_message = re.escape(user_message) Prevention
- Prefer plain substrings over regex when full pattern matching isn't needed.
- Run re.compile() on hand-written filter patterns before committing them.
- Use re.escape() on dynamic substrings embedded in filter regexes.
When it happens
Trigger: A filter whose message or module field contains invalid regex syntax, e.g. 'ignore:[unbalanced::DeprecationWarning' (unmatched bracket) or 'ignore:msg:*bad::DeprecationWarning'. When escape=False (ini/filterwarnings mark) the raw string is compiled; when escape=True (command-line -W) re.escape is applied first, so this most often triggers from ini/mark filters with hand-written regex.
Common situations: Writing a partial regex in filterwarnings without escaping special chars; unbalanced parentheses/brackets in the message pattern; using a glob-style '*' expecting shell semantics instead of regex.
Related errors
- number is negative
- invalid lineno {lineno_!r}: {e}
- while parsing the following warning configuration: {arg}
- {cat} is not a Warning subclass
- absolute tolerance can't be NaN.
AI-assisted analysis of pytest-dev/pytest@98b357f69e (2026-08-04).
Data as JSON: /data/errors/fc62040c9ce5398a.json.
Report an issue: GitHub.