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?
5 Answers
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.
I love that out-of-the-box thinking!
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.
For sure! It's good to think about variations and not just stick to one style.
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.
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.
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.
Thanks for the suggestion! I definitely lean towards the more readable approach.
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.