I'm trying to improve my regex for identifying float numbers in a string. I currently have this regex: `^-?(d+.d*|d*.d+)$`, which works for inputs like `-90.`, `.67`, and `42.6`, but it fails to recognize just a decimal point `.` or a negative decimal `-.` as invalid. I'm looking for a regex that accommodates numbers that can have digits on either side of the decimal point while enforcing the rule that there must be at least one digit present. Any suggestions?
4 Answers
Your regex isn't bad, but keep in mind that various programming languages interpret regex differently. There are many ways to construct a float-checking regex, and you might want to optimize for readability and maintainability.
Just a reminder: it's worth noting that a float might start with a + sign or have an exponent like `+1.21E-6`. Additionally, numbers like `10` without a decimal are still considered valid floats in many languages, so keep that in consideration when forming your regex.
Hmm, I'm not sure if I need to accommodate exponent formats for my project.
Yours is probably the most readable one I've seen so far. You might also consider something like `^-?d*(d.|.d)d*$` for clarity and to satisfy more cases.
Thanks for the suggestion! I find mine much easier to read too.
Instead of getting too deep into regex, you might want to consider just converting the string to a float and handling exceptions. If it throws an error, then it’s not a valid float. Some languages also offer a method like TryParse() which is cleaner and provides a success flag plus the result. If you're preparing data for another system, matching its float rules is better, but otherwise, using built-in checks is usually sufficient.
I love out-of-the-box thinking!
Exactly! It keeps things simple and efficient.
Good point! It can be tricky to ensure portability across platforms.