What’s a better regex for validating floats?

0
32
Asked By CuriousCoder42 On

I'm working on a regex to check if a given string is a float and I want it to handle both cases where there are digits before and/or after the decimal point, while ensuring there's at least one digit. The regex I'm currently using is `^-?(d+.d*|d*.d+)$`. This matches inputs like `-90.`, `.67`, and `42.6`, but it fails for `.` and `-.`. Any suggestions for improvement?

5 Answers

Answered By RegexNinja99 On

Have you considered that, depending on the programming language, it might be easier to just try converting the string to a float? You could catch exceptions if the conversion fails, which might simplify things for you!

ThoughtfulTabby -

I love out-of-the-box thinking!

CodeAnalyzer88 -

Some languages offer a method like TryParse(), which could avoid exceptions. It returns a simple Boolean flag to indicate whether the conversion succeeded, which might suit your needs better!

Answered By FloatFanatic On

Don’t forget that a float can also begin with a `+` or have an exponent. For example: `+1.21E-6`. And also keep in mind that most languages will consider `10` a valid float even though there’s no decimal point.

InquisitiveUser -

Hmm, I'm not sure if I need to account for exponents. I'm practicing with a project where I’m intentionally separating floats and ints.

Answered By PatternGuru22 On

Your regex isn’t bad! Just remember that there are many ways to define floats in regex, and it's all about what you need to match. A different approach might be using `^-?d*(d.|.d)d*$`, which could work better for your goals.

HelpfulHan -

Thanks! I agree that I find mine more readable too.

Answered By FloatMaster3000 On

Another version of your regex could be: `^-?(d+?.d*|.d+)$`. This ensures there's at least one digit on either side of the decimal, which should help filter out invalid strings like `-` or `.`!

Answered By DetailDude On

Your regex might match values like `005.12`, which is technically okay, but not how many people write floats. You should also consider the case of `2.`, which is uncommon and could signal a formatting error.

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.