What’s the best regex to validate a float?

0
11
Asked By CuriousCoder42 On

I'm working on a regex to determine if a line represents a float. My current regex is `^-?(d+.d*|d*.d+)$`, which manages to capture scenarios like `-90.`, `.67`, and `42.6`. However, it does not accept inputs like `.` or `-.` and I'm wondering if there's a better alternative that ensures at least one digit is present before or after the decimal point. Any suggestions?

6 Answers

Answered By RegexNinja99 On

Instead of relying solely on regex, you might consider trying to convert the string to a float directly. If it fails, you can catch the exception. This could simplify your checks significantly! Also, some languages offer TryParse methods which can return a success flag and the result without the overhead of an exception.

ThoughtfulDev -

I love the out-of-the-box thinking here!

DataCleaner22 -

Totally, and if you're just cleaning up data for another system, better to match what that system needs and use your language's built-in checker for validation.

Answered By UserNameDeleted On

[deleted]

TryHarder99 -

It doesn’t seem to work with the first example provided.

Answered By FloatEnthusiast On

Your regex is likely the most readable I've seen. Another option could be like this: `^-?d*(d.|.d)d*$`, which still captures the necessary cases for floats.

CuriousCoder42 -

Thanks! I appreciate that—readability is key.

Answered By SyntaxSavvy On

A couple of things to note: you might want to allow for a '+' at the start of floats. And some languages treat integers like `10` as valid floats too, even without a decimal.

CuriousCoder42 -

Hmm, I wasn't expecting to handle the exponent format yet. I'm working with some projects on GitHub and separating floats from ints for now.

Answered By CriticalThinker On

Your regex supports leading zeros like `005.12`, which is valid but not how most people typically write floats. It also permits something like `2.`, which is kind of odd—might indicate input errors completely.

Answered By RegexWhiz On

Your regex isn't bad, but keep in mind there are various ways to define floats. Just a heads up, your current one won't catch scientific notation like `1.3e3` or `1.3e-3`. Consider that if it's important for your use case!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.