I have this regex pattern for checking if a line is a float: `^-?(d+.d*|d*.d+)$`. I'm trying to ensure that it correctly matches floats, with at least one digit present before or after the decimal point. It currently works for examples like `-90.`, `.67`, and `42.6`, but it doesn't match just `.` or `-.`. I'm looking for suggestions on how to improve it!
4 Answers
Instead of relying solely on regex, you might want to consider converting the string to a float directly in your coding language and catching any exceptions if it fails. This can often be simpler and avoids complications with regex.
That’s a great suggestion! I appreciate the creative approach.
Your regex could also match non-standard cases like `005.12` or `2.`, which might not be how people usually write floats. Just something to consider when you're validating input!
If you want to be super thorough, remember that floats can also have signs like `+` and exponents like `1.21E-6`. Keep that in mind depending on your use case!
I hadn’t thought about the exponent format yet. Thanks for the tip!
Your regex is pretty readable! Another option could be `^-?d*(d.|.d)d*$` for matching floats without causing confusion.
I like your suggestion! It looks cleaner.
And some languages offer 'TryParse()' methods, which can simplify the process even more.