DEV Community

loading...

Accurately Judge Data Types by Using Regex

vonhyou profile image Your 🍟 Classmate ・1 min read

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

Discussion (0)

Forem Open with the Forem app