I'm working on a regex to determine if a line represents a float. My current regex is `^-?(d+.d*|d*.d+)$`, which manages to capture scenarios like `-90.`, `.67`, and `42.6`. However, it does not accept inputs like `.` or `-.` and I'm wondering if there's a better alternative that ensures at least one digit is present before or after the decimal point. Any suggestions?
6 Answers
Instead of relying solely on regex, you might consider trying to convert the string to a float directly. If it fails, you can catch the exception. This could simplify your checks significantly! Also, some languages offer TryParse methods which can return a success flag and the result without the overhead of an exception.
Totally, and if you're just cleaning up data for another system, better to match what that system needs and use your language's built-in checker for validation.
[deleted]
It doesn’t seem to work with the first example provided.
Your regex is likely the most readable I've seen. Another option could be like this: `^-?d*(d.|.d)d*$`, which still captures the necessary cases for floats.
Thanks! I appreciate that—readability is key.
A couple of things to note: you might want to allow for a '+' at the start of floats. And some languages treat integers like `10` as valid floats too, even without a decimal.
Hmm, I wasn't expecting to handle the exponent format yet. I'm working with some projects on GitHub and separating floats from ints for now.
Your regex supports leading zeros like `005.12`, which is valid but not how most people typically write floats. It also permits something like `2.`, which is kind of odd—might indicate input errors completely.
Your regex isn't bad, but keep in mind there are various ways to define floats. Just a heads up, your current one won't catch scientific notation like `1.3e3` or `1.3e-3`. Consider that if it's important for your use case!
I love the out-of-the-box thinking here!