{"id":"fc62040c9ce5398a","repo":"pytest-dev/pytest","slug":"invalid-regex-e-pattern-r-e","errorCode":null,"errorMessage":"Invalid regex {e.pattern!r}: {e}","messagePattern":"Invalid regex (.+?): (.+?)","errorType":"exception","errorClass":"UsageError","httpStatus":null,"severity":"error","filePath":"src/_pytest/config/__init__.py","lineNumber":2320,"sourceCode":"        message = re.escape(message)\n    if module and escape:\n        module = re.escape(module) + r\"\\Z\"\n    if lineno_:\n        try:\n            lineno = int(lineno_)\n            if lineno < 0:\n                raise ValueError(\"number is negative\")\n        except ValueError as e:\n            raise UsageError(\n                error_template.format(error=f\"invalid lineno {lineno_!r}: {e}\")\n            ) from None\n    else:\n        lineno = 0\n    try:\n        re.compile(message)\n        re.compile(module)\n    except re.error as e:\n        raise UsageError(\n            error_template.format(error=f\"Invalid regex {e.pattern!r}: {e}\")\n        ) from None\n    return action, message, category, module, lineno\n\n\ndef _resolve_warning_category(category: str) -> type[Warning]:\n    \"\"\"\n    Copied from warnings._getcategory, but changed so it lets exceptions (specially ImportErrors)\n    propagate so we can get access to their tracebacks (#9218).\n    \"\"\"\n    __tracebackhide__ = True\n    if not category:\n        return Warning\n\n    if \".\" not in category:\n        import builtins as m\n\n        klass = category","sourceCodeStart":2302,"sourceCodeEnd":2338,"githubUrl":"https://github.com/pytest-dev/pytest/blob/98b357f69e380da908740a212288d73b2ee06687/src/_pytest/config/__init__.py#L2302-L2338","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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)."],"exampleFix":"# before (unbalanced bracket)\n[pytest]\nfilterwarnings = [\"ignore:[unbalanced:DeprecationWarning\"]\n\n# after\n[pytest]\nfilterwarnings = [\"ignore:\\[unbalanced:DeprecationWarning\"]","handlingStrategy":"validation","validationCode":"import re\ndef validate_filter_regex(message: str, module: str) -> None:\n    for label, pattern in (('message', message), ('module', module)):\n        if pattern:\n            try:\n                re.compile(pattern)\n            except re.error as e:\n                raise ValueError(f'Invalid {label} regex {pattern!r}: {e}') from None","typeGuard":"import re\ndef is_valid_regex(pattern: str) -> bool:\n    try:\n        re.compile(pattern)\n        return True\n    except re.error:\n        return False","tryCatchPattern":"import re\ntry:\n    re.compile(user_message)\nexcept re.error as e:\n    print(f'message field is not valid regex: {e}'); user_message = re.escape(user_message)","preventionTips":["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."],"tags":["pytest","config","warnings","filterwarnings","regex","validation"],"analyzedSha":"98b357f69e380da908740a212288d73b2ee06687","analyzedAt":"2026-08-04T20:26:34.442Z","schemaVersion":2}