I have this regex to test if the user input is valid:
value.length === 0 ||
value === '-' ||
(!isNaN(parseFloat(value)) && /^-?\d \.?\d*$/.test(value))
The main point is in the regex: /^-?\d \.?\d*$/
. However sonarcloud is feeling it as a security hotspot saying:
Make sure the regex used here, which is vulnerable to super-linear runtime due to backtracking, cannot lead to denial of service.
I guess it's because of the double digit test, but I couldn't find a way to avoid it. Is it a security threat, or harmless?
CodePudding user response:
The warning is caused by the optional .
between two groups of digits. This could mean that a regex engine would backtrack to match fewer digits with \d
and more with \d*
, but always coming to the same conclusion: it doesn't match.
You can avoid this as follows:
^-?\d (\.\d*)?$
This way the only time the \d*
pattern comes into play, is when there is a separating dot. This means there is no possibility for the same input character to be considered for the \d
pattern, and later (after backtracking) for the \d*
pattern.