I'm currently using this regex to check if a line contains a float value: `^-?(d+.d*|d*.d+)$`. It works for numbers like `-90.`, `.67`, and `42.6`, but it doesn't match just a dot (`.`) or negative dot (`-.`). I'm looking for suggestions to make this more robust to ensure it captures valid float representations, including cases with at least one digit on either side of the decimal. Any ideas?
6 Answers
Your regex is decent, but keep in mind there are various ways to interpret a float in regex. For instance, it doesn't account for scientific notation like `1.3e3`. Just something to consider!
Another version that meets your needs could be `^-?(d+?.d*|.d+)$`, ensuring there's a digit on both sides of the decimal. It won't match just a dot or a negative sign, meeting your requirements directly.
Just a heads up, your regex will match numbers like `005.12`, which isn't how people usually format floats. It will also match cases like `2.`, which could point to input errors.
Instead of relying solely on regex, you might find it easier to convert the string to a float directly and catch any exceptions. This approach can vary by programming language, but it often simplifies things. Plus, some languages offer functions like TryParse() that can check for valid floats without the overhead of exceptions.
You make a good point! For validating input, referencing what the target system accepts can ensure smoother integration.
I love that out-of-the-box thinking!
While your regex is readable, another option could be `^-?d*(d.|.d)d*$`. It's a little more concise and still meets your criteria.
Thanks! I appreciate that perspective. I also find readability important!
Remember, a valid float can also start with a plus sign and include exponents, like `+1.21E-6`. Even whole numbers like `10` should technically be considered floats depending on the language you're using.
That's a good point! I'm focusing on separating floats from integers, so I'm not set on accepting scientific notation just yet.
Exactly! Regex can be tricky because there are definitely differing standards.