So in one of my views I am using regex which is looking like that:
RegExp('^(?!(.|\n)*{\/?.+})(.|\n)*$')
ANd sonarlint is giving me a warning about catastrophic backtracking and should make sure that I should use a regex that cannot lead to denial of service. From what I have read it mostly happens on regexes that are not too complex and are using a lot of "any" character calls like . or +
This is the first time for me to see a security hotspot like this, should I try to rewrite this regex or is it complex enough so it won't trigger catastrophic backtracking
There are a couple of points to note here:
(.|\n)*
construct causes very poor performance due to excessive backtracking. See "Why (?:\s|.)*
is a bad pattern to match any character including line breaks" YouTube video with detailed explanation of why this is a very bad pattern. All you need is a [^]
construct to match any chars./^(?![^]*{[^}]*})[^]*$/
, or even /^(?![^]*{[^}]*})/
since JavaScript regex functions do not require full string match. All you need here is to actually use {[^}]*}
pattern and negate the result with !
.So you can use
if !(/{[^}]*}/.test(text)) {
return true;
}
where {[^}]*}
matches a {
, then any zero or more chars other than }
and then a }
char.