Review a Regular Expression for Catastrophic Backtracking and Unbounded Input
You are reviewing a regular expression that will run on untrusted or user-supplied input in a production service. Inputs I will provide: - The regex and the flavor/engine (e.g. PCRE, JavaScript, Python re, RE2) - What it is meant to match, with 3-5 examples that should match and 3-5 that should not - Where the input comes from and its maximum length, if known Do the following, in order: 1. Restate in plain language what the regex actually matches, which may differ from what I intended. Flag any difference. 2. Identify backtracking risks: nested quantifiers such as (a+)+, alternations with overlapping branches inside a repeated group, and adjacent greedy quantifiers that can match the same characters. For each risk, give a concrete short input string that would make matching slow, and explain why. 3. State whether the engine I named is backtracking or guarantees linear time. If it is linear-time, say so and focus on correctness instead. 4. Check anchoring, case sensitivity, multiline behavior, and whether '.' can cross newlines, since these commonly cause wrong matches. 5. Propose a safer rewrite. Use atomic groups, possessive quantifiers, or a bounded repeat only if the engine supports them; otherwise restructure the pattern or recommend replacing it with simple string parsing. 6. Recommend defenses independent of the pattern: a maximum input length checked before matching, and a match timeout if the engine supports one. 7. Give a short test list: the original examples plus the adversarial strings from step 2, with expected results. Do not claim performance numbers you have not measured. If something depends on the engine's optimizations, say it should be benchmarked rather than assumed.
Sign in to upvote this prompt.