I'm working with a regex that checks if a line contains a float, but I want to make sure it captures both cases where there are digits before or after the decimal point while ensuring there's at least one digit overall. Right now, I'm using: `^-?(d+.d*|d*.d+)$`. This works for examples like `-90.`, `.67`, and `42.6`, but it doesn't match just `.` or `-.`. Any suggestions for a better regex?
3 Answers
If you’re looking for another approach, you might try: `^-?(d+?.d*|.d+)$`. This one ensures that there's at least one digit on either side of the decimal point, effectively ruling out entries like `-` or `.`.
Don’t forget that a valid float could start with a plus sign and may include an exponent, like `+1.21E-6`. Also, most languages consider integers like `10` valid floats, even though they lack a decimal point.
Instead of relying solely on regex, you could consider converting the string to a float and catching exceptions if it fails. Some programming languages even have a `TryParse()` method that checks for validity without bothering with exceptions. This can simplify things a lot! If you're sanitizing inputs for another system, ensure your regex matches that system's requirements. Just a thought!
That’s true! Using something like TryParse avoids the overhead of exception handling for invalid floats.
I love that out-of-the-box thinking!
Good to know! I’m currently working on something where I’m parsing floats separately from integers.