What’s a better regex for validating floats?

0
0
Asked By CuriousCoder42 On

I'm trying to improve my regex for checking if a line represents a float. Currently, I'm using this regex: `^-?(d+.d*|d*.d+)$`. This works for inputs like `-90.`, `.67`, and `42.6`, but I want to ensure it captures floats correctly, including scenarios with numbers before and after the decimal. However, it shouldn't match `.` or `-.`. Any suggestions for a better approach?

6 Answers

Answered By DevMotivation On

Another thing to consider is that floats can start with a '+', and they might also have exponents, like `+1.21E-6`. Also, note that most languages would still consider `10` as a valid float even without a decimal point.

CuriousCoder42 -

I wasn't planning to include exponents, but that's a good point for future reference!

Answered By PragmaticTester On

One more thing: your regex will match strings like `005.12`, which isn't how most people write floats. It also allows `2.`, which can look weird and suggest there might be an input error.

Answered By SimpleExpressions On

If you're looking for readability, I think yours is pretty clear! You could try tweaking it to something like `^-?d*(d.|.d)d*$` for a bit more flexibility.

CuriousCoder42 -

Thanks! I'm all for keeping things readable.

Answered By RegexGuru99 On

Honestly, depending on the programming language you're using, it might be easier to just try converting the string to a float and see if it throws an exception. It's a more straightforward approach for checking validity without dealing with regex.

DataNerd88 -

Exactly! Some languages also offer a method like TryParse() which gives you a success flag along with the parsed result if it worked. It's way less overhead than catching exceptions.

QuestionAsker -

I like that idea! It feels less complicated to handle.

Answered By RegexWhiz On

Your regex isn’t bad, but remember that regex syntax can vary a lot. There are definitely different formats to define floats in regex. For example, if you want your regex to also capture scientific notation or integers, you might need to adjust it a bit.

FloatFanatic -

Right! And that reminds me, your current regex won't catch cases like `1.3e3` or `1.3e-2`, which might be important depending on your requirements.

Answered By [deleted] On

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.