I'm trying to create a regex pattern that can effectively identify float numbers. My current regex is `^-?(d+.d*|d*.d+)$`, which works well for cases like `-90.`, `.67`, and `42.6`, but it fails for just `.` or `-.`. Is there a more efficient way to cover different float formats, ensuring at least one digit is present before or after the decimal point?
6 Answers
If you're looking to match exactly one digit on either side of the decimal, you might want to use: `^-?(d+?.d*|.d+)$`. This won't allow for just `-` or `.` since those have no digits.
Don't forget that floats can start with a `+` and may include exponents, like `+1.21E-6`. Also, many languages view `10` as a valid float without requiring a decimal point.
Instead of relying on regex, depending on the programming language you're using, you could just try converting the string to a float directly. If it fails, catch the exception. It's often simpler than writing complex patterns!
That's a solid point! It's a creative way to handle it.
Some languages have a method like TryParse() that avoids exceptions, giving you a success flag instead. But if you're sanitizing input for another system, you'll want to match what they accept.
Yours is pretty readable! You could also consider a pattern like `^-?d*(d.|.d)d*$` which covers floats well.
Thanks! I really do find mine more straightforward.
Your regex isn't bad! Just remember, regex can vary between languages and there are numerous ways to define a float. So there might be simpler options out there.
Exactly! For instance, it won't match scientific notation like `1.3e3` or `1.3e-3`.
Just a heads up, your regex will still match values like `005.12`, which although valid, might not be how most people write floats. Plus, it accepts `2.` which could indicate a user input mistake.
Good point! I didn't plan to include exponent formats for now since I'm separating floats and ints in my project.