DEV Community

Regular 🍟
Regular 🍟

Posted on

2 2

Accurately Judge Data Types by Using Regex

Time: 2021-04-12 11:56 UTC+8:00

Author: Me

It's not easy to judge a string's content's type in a normal way. So, it's time for regular expressions.

Integers

isInteger       = /^-?\d+$/                             # for integers
isPositiveInt   = /^[0-9]*[1-9][0-9]*$/     # for positive integers
isNegativeInt   = /^-[0-9]*[1-9][0-9]*/     # for negative integers
isNonPosiInt    = /^((-\d+)|(0+))$/             # for non-positive integers
isNonNegaInt    = /^\d+/                                    # for non-negative integers
Enter fullscreen mode Exit fullscreen mode

Floats

isFloat         = /^(-?\d+)(\.\d+)?/                                # for floats
isPositiveFloat = /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/                                                                                         # for positive floats
isNegativeFloat = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/                                                                               # for negative floats
isNonPosiFloat  = /^((-\d+(\.\d+)?)|(0+(\.0+)?))$/  # for non-positive floats
isNonNegaFloat  = /^\d+(\.\d+)?$/                                       # for non-negative floats
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay