MediumPython

Fix Catastrophic Regex (ReDoS)

PythonSecurityReliability

The function below validates a username using a regular expression with a nested quantifier: ^([a-z0-9_]+)+$.

The bug: this pattern is vulnerable to Regular Expression Denial of Service (ReDoS). For certain crafted inputs, the regex engine's backtracking takes exponential time — a string of ~25 valid characters followed by one invalid character can hang for seconds, blocking the process.

Your task: fix solve(username) so it validates the same rule — 3 to 20 lowercase letters, digits, or underscores — without the vulnerable nested-quantifier pattern.

solve('john_doe')  # → True
solve('jo')        # → False (too short)
solve('John_Doe')  # → False (uppercase not allowed)

Sample tests

Test #1Valid username
Input: ["john_doe"]
Output: true
Test #2Too short
Input: ["jo"]
Output: false
Test #3Uppercase not allowed
Input: ["John_Doe"]
Output: false
Test #4Hyphen not allowed
Input: ["user-name"]
Output: false