I'm currently using the regex `^-?(d+.d*|d*.d+)$` to check if a string is a valid float. It works for inputs like `-90.`, `.67`, and `42.6`, but it fails for just `.` or `-.`. I'm looking for ways to improve this regex so it can handle digits before and after the decimal point while ensuring at least one digit is present. Any suggestions?
6 Answers
Just a heads up—your regex will match numbers like `005.12`, which is technically valid but not typically how floats are represented. Also, `2.` might show up in your matches, which could indicate an input error.
You might consider just trying to convert the string to a float, depending on the programming language you're using. If the conversion fails, then you can catch the exception. It's a straightforward way to handle it without overcomplicating your regex.
Some languages even have a `TryParse()` method that checks validity without the overhead of exceptions, returning a success flag and the result.
If you're looking for readability, you might try something like `^-?d*(d.|.d)d*$`. It keeps it simple and clear.
Thanks! I appreciate the suggestion; readability is important to me.
A more precise regex based on your needs could be `^-?(d+?.d*|.d+)$`. This ensures at least one digit on either side of the decimal, and it won't match just `-` or `.` since those don't contain digits.
Your current regex isn't bad! However, remember that regex can vary by language, and there are many formats for defining floats.
True! For example, your regex might not account for scientific notation like `1.3e3` or `1.3e-3`.
Also, keep in mind that valid floats can start with a `+` sign or include an exponent, like `+1.21E-6`. And in many languages, `10` would also be considered a float even without a decimal point.
That's a good point! I'm focusing on separating floats and ints, so I'm not considering exponents right now.
That's a clever approach! It really simplifies things.