[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: ReDOS and RegExp in javascript: be careful when matching end of string



On 7/24/25 11:47, Jérémy Lal wrote:
Hello,

RegExp needs to be anchored to something.
This seemingly innocuous RegExp is vulnerable to ReDOS:
/a+$/

To fix it, it needs to be anchored to something:
/([^a]|^)a+$/

If one knows that the string is has something else before, it simplifies to:
/[^a]a+$/

console.time("redos");
('a'.repeat(50000) + '\x00a').match(/a+$/);
console.timeEnd("redos")
redos: 2.506s

console.time("no redos");
('a'.repeat(50000) + '\x00a').match(/[^a]a+$/);
console.timeEnd("no redos")
no redos: 0.639ms

See you !
Jérémy

Thank you,

by the way, "(?:)" [non capturing] is always faster than "()", but last solution stays the best:

/a+$/          : 1.449s
/([^a]|^)a+$/  : 0.173ms
/(?:[^a]|^)a+$/: 0.155ms
/[^a]a+$/      : 0.117ms


Reply to: