I'm trying to improve my regex for checking if a string is a float. Currently, I have `^-?(d+.d*|d*.d+)$`. This works for numbers like `-90.`, `.67`, and `42.6`, but it doesn't recognize single dots `.` or negative single dots `-.` as valid. I'm looking for a way to ensure that there are digits both before and/or after the decimal point while preventing those invalid cases.
7 Answers
Keep in mind that a float can also start with a + and may have an exponent, e.g., `+1.21E-6`. Also, just to note, `10` is a valid float too, even without a decimal point.
Yours is quite readable, but you could also try something like `^-?d*(d.|.d)d*$` for clarity. That keeps the same checks but may look nicer!
Thanks for the tip! I agree that readability is key!
Another way to refine it is with `^-?(d+?.d*|.d+)$`, while still making sure there's at least one digit around the decimal. This won’t allow `-` or `.` since neither has digits.
Your regex matches inputs like `005.12`, which are valid but not how people typically write floats. It also accepts `2.`, which seems off since that’s not common.
Your regex isn't bad! Just remember that regex can vary, and there are multiple ways to define what a float is. It might be worth exploring those alternatives.
True! Your regex doesn’t match numbers like 1.3e3 or 1.3e-3, which could be important.
You might consider using string-to-float conversion instead; just try converting and catch exceptions for invalid cases. It can be simpler depending on the language you're using!
That's some great out-of-the-box thinking!
Some languages have methods like TryParse() which could help here. It checks if conversion works and returns a flag without throwing an exception. So if you need to clean your data for another system, ensure you know what formats are accepted there!
[deleted]
Your regex fails to match the first example of valid inputs.
Good point! I hadn't considered the exponent format since I'm separating floats from integers for this project.