Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Match negative/positive float/int regex – is it evil?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading