I'm working on a regex to check if a given string is a float and I want it to handle both cases where there are digits before and/or after the decimal point, while ensuring there's at least one digit. The regex I'm currently using is `^-?(d+.d*|d*.d+)$`. This matches inputs like `-90.`, `.67`, and `42.6`, but it fails for `.` and `-.`. Any suggestions for improvement?
5 Answers
Have you considered that, depending on the programming language, it might be easier to just try converting the string to a float? You could catch exceptions if the conversion fails, which might simplify things for you!
Some languages offer a method like TryParse(), which could avoid exceptions. It returns a simple Boolean flag to indicate whether the conversion succeeded, which might suit your needs better!
Don’t forget that a float can also begin with a `+` or have an exponent. For example: `+1.21E-6`. And also keep in mind that most languages will consider `10` a valid float even though there’s no decimal point.
Hmm, I'm not sure if I need to account for exponents. I'm practicing with a project where I’m intentionally separating floats and ints.
Your regex isn’t bad! Just remember that there are many ways to define floats in regex, and it's all about what you need to match. A different approach might be using `^-?d*(d.|.d)d*$`, which could work better for your goals.
Thanks! I agree that I find mine more readable too.
Another version of your regex could be: `^-?(d+?.d*|.d+)$`. This ensures there's at least one digit on either side of the decimal, which should help filter out invalid strings like `-` or `.`!
Your regex might match values like `005.12`, which is technically okay, but not how many people write floats. You should also consider the case of `2.`, which is uncommon and could signal a formatting error.

I love out-of-the-box thinking!