I'm trying to find a regex pattern to check if a line contains a float. I need it to account for both digits before and after the decimal point, but there should be at least one digit somewhere in there. Currently, I'm using this regex: `^-?(d+.d*|d*.d+)$`. It seems to work fine because it matches cases like `-90.`, `.67`, and `42.6`, but it doesn't match just a dot `.` or negative dot `-.`. Is there a better way to handle this?
7 Answers
Note that floats can also start with a plus sign or include exponents like `+1.21E-6`. Also, remember `10` is valid without a decimal point in many languages.
I wasn't considering exponents for this project, as I'm trying to keep floats and ints distinct. But that’s a good point!
Instead of focusing solely on regex, consider just trying to convert the string to float directly in your programming language. If it fails, you catch the exception. This can be a simpler approach depending on what language you’re using!
Exactly! If you want to make this robust for external systems, you'll need to ensure your regex aligns with what they accept.
That's a clever approach! Some languages do have a TryParse() method that can check if conversion succeeds without throwing errors, which might be worth looking into.
I find your regex quite readable! Another variant you could try is `^-?d*(d.|.d)d*$`. It might also work well for your case.
Thanks! I also think readability is key in regex.
Your regex will also match entries like `005.12`, which is technically a float, but it’s not a common way to write them. Also, `2.` could hint at an input error since it's not typical to end floats like that.
Your regex isn't bad, but remember that regex flavors can differ, and floats can be defined in various ways. It might be useful to adapt your regex based on context.
Very true! What about floats in scientific notation, like `1.3e3`? This current regex wouldn't catch those.
For what you're trying to achieve, here’s another regex: `^-?(d+?.d*|.d+)$`. It meets the requirement of having at least one digit around the decimal point, avoiding invalid entries like `-` or `.`.
This fails with your first example of valid inputs.