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?
4 Answers
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.
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.
For sure! It's good to think about variations and not just stick to one style.