I'm looking for a better regex pattern to check if a given string is a valid float. My current regex is `^-?(d+.d*|d*.d+)$`, which handles numbers like `-90.`, `.67`, `42.6`, etc. However, it doesn't accept `.` or `-.`. I want a solution that allows for digits on both sides of the decimal point while ensuring at least one digit is present. Any suggestions?
5 Answers
Another option could be `^-?d*(d.|.d)d*$`. It's more concise and still quite readable, while adhering to your requirement for at least one digit around the decimal point.
One approach you might consider is to use float conversion instead of regex validation. Depending on the programming language, you can try to convert the string to a float and catch any exceptions if the conversion fails. This can sometimes be simpler and more efficient than regex checking.
That's a great idea! It's good to think outside the box. Some languages also offer methods like TryParse() that provide a success flag along with the result, which might be even better for your needs.
Exactly! If you're cleaning up data for another system, you might need to align your regex with that system's float definitions, but utilizing built-in checks is a good default.
Your current regex isn't bad. Just keep in mind that different regex flavors exist, and there are multiple ways to define a valid float. You might want to adjust based on that.
True! By the way, your regex doesn't account for scientific notation like `1.3e3` or `1.3e-3`, which could be useful depending on your situation.
If you're considering a broader definition of floats, remember that they can start with a `+` and can also use an exponent notation like `+1.21E-6`. Also, plain integers like `10` are often considered valid floats even without a decimal point.
Good point! I'm not really focusing on the exponent format since I'm working on a LISP project where I’m keeping floats and ints separate.
Just a heads-up, your regex will match representations like `005.12`, which is technically fine but not typical for floats. Also, it allows `2.`, which is unusual and might suggest input error. You might want to refine it.
Agreed! It could lead to some odd outputs that confuse users.
Thanks! I find that version appealing as well, very straightforward!