What’s a better regex for detecting floats?
Asked by
CuriousCat123
I'm trying to improve my regex for identifying float numbers. The current regex I have is `^-?(d+.d*|d*.d+)$`, which works for cases like `-90.`, `.67`, and `42.6`. However, it doesn't accept inputs like `.` or `-.`, and I'm wondering if there's a better way to handle digits before and after the decimal point while ensuring at least one digit is present. Any suggestions?
Answers
If you're looking for readability, try something like `^-?d*(d.|.d)d*$`. It’s simpler and covers the need for at least one number on either side of the decimal.
Reply to this answer
Your regex would match things like `005.12`, which isn’t typically how floats are expressed. It also allows for odd formats like `2.`, which might indicate input errors. Consider refining your criteria for what constitutes a valid float.
Reply to this answer
Here's another version that matches a valid float while ensuring there's at least one digit on either side of the decimal: `^-?(d+?.d*|.d+)$`. This will prevent false positives like `-` or `.` as valid floats.
Reply to this answer
Your regex is decent. Just remember, there are multiple ways to define floats in regex. You might need to consider options for scientific notation, like `1.3e3`, too. Also, keep in mind cases where a float can be presented without a decimal, like `10` which is still a valid float.
PrecisionSeeker: For sure! It's good to think about variations and not just stick to one style.
Reply to this answer
Instead of relying solely on regex, consider using the built-in string-to-float conversion of your programming language. If it fails, you can handle the exception. Some languages even have methods like TryParse() that can cleanly check if something can be converted to a float without throwing an error. This keeps things efficient without complicated regex.
ThoughtfulCoder: I love that out-of-the-box thinking!
DataCleaner: If you're cleaning data for another system, make sure you check what float formats it accepts first, then use the built-in methods to validate and convert.
Reply to this answer
Add your answer
Answers are reviewed before publication.
RegexEnthusiast: Thanks for the suggestion! I definitely lean towards the more readable approach.