/^(\-|\+)?([0-9]+|Infinity)$/
I've seen this multiple times when I'm looking to filter things. There are many variations but it usually always starts with (/ then something. Recently I found this as a suggestion to help parse a string and make sure it has only numbers in it. On Mozilla's js page for RegExp I found some other operators but it didn't include nearly all that are above.
This is a regular expression. The one you pasted would match a positive/negative whole number, or match the word infinity. In short, a regular expression is:
A regular expression (regex or regexp for short) is a special text string for describing a search pattern. You can think of regular expressions as wildcards on steroids.
http://www.regular-expressions.info/
You often see regular expressions written as /expression_here/
because these slashes in many programming languages are a shorthand way for developers to build regular expression objects.
You could create a simple expression to match a number with something like:
/^[0-9]*$/.test('44') // returns true
and
/^[0-9]*$/.test('asdasd') // returns false
Expressions like these and like the one you've pasted are parsed and turned into little machines (called finite state machines). the entire purpose of the machine is to determine if a string is a match for the expression the machine represents, or if it is not a match. You can then feed a string into such a machine and it will spit back the answer to you.
In our example above, we feed the strings 44
and asdasd
into a regular expression /^[0-9]*$/
using the test
method, and it returns true
because 44
matches the expression and false
for asdasd
because it does not match.
We can break up the regular expression that you included in your post as well:
^
means that the regular expression has to match starting from the VERY beginning of the string
(\-|\+)
means start at the beginning of the string and match either -
or +
, the question mark means this part is optional
[0-9]+|Infinity
means "match one or more numbers from 0 to 9", OR (|
) match the text Infinity
$
means, "and then require that the string ends here"
It's a regular expression that will match positive/negative natural numbers or Infinity
.
/^(\-|\+)?([0-9]+|Infinity)$/
^(\-|\+)
- Match the beginning of the string for either the -
or +
literal character(s).
?
- The preceding expression, which are the -
/+
characters, are optional. In other words, the expression can be matched 0 or 1 times.
([0-9]+|Infinity)$
- The end of the string should be 1 or more digits or the string Infinity
.
// Matches:
'-100'.match(/^(\-|\+)?([0-9]+|Infinity)$/);
'+100'.match(/^(\-|\+)?([0-9]+|Infinity)$/);
'Infinity'.match(/^(\-|\+)?([0-9]+|Infinity)$/);
// Does NOT match:
'5%'.match(/^(\-|\+)?([0-9]+|Infinity)$/);
'20/1'.match(/^(\-|\+)?([0-9]+|Infinity)$/);
'NaN'.match(/^(\-|\+)?([0-9]+|Infinity)$/);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With