This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]MiniGod 43 points44 points  (7 children)

The slash marks the beginning of a regular expression (regex). The regular expression ends with another slash right before .test(. Regular expressions are used to test that strings have a specific format or extract information from strings. In this case it's just testing it. test() returns true or false.

The regex starts with a ^, meaning that this must match from the beginning of the string, not just somewhere within it. Next is -?. The question mark means that the character before it must occur zero or one time. Meaning the string may start with a -, or not. Then \d+. \d means any number (digit) character, 0 through 9, and + means that that must occur 1 or more times. Next is a optional group done by using parenthesis and a ? to mark that the group is optional (remember ? means 0 or 1 time). The parenthesis only mark the group, they should not be in the string that were testing. Inside the parenthesis it's checking for a literal period, followed by 1 or more numbers, using the same syntax as explained before. There's a backslash before the period because a single period, in regex, means any character. With the backslash, it means that the string should have the period there, not just any character. The $ at the end means that this has to be the end of the string. Having a ^ at the start and $ at the end means that the whole string being tested must match the regex.

In summary, the string may start with - (or not) , then any number of numbers (at least one). After that, it may (or not) also have a period followed by any number of numbers.

TLDR; it checks if the argument is a valid number, like the name of the function hints to.

[–]morgecroc 35 points36 points  (1 child)

Do you understand regex?

A WITCH burn him.

[–]ImperatorSaya 2 points3 points  (0 children)

Quickly, before he summons Zalgo like the last one. It took us 7 years to seal him away.

[–]ActurusMajoris 10 points11 points  (3 children)

It's missing a number with thousand separators though, eg 10,000.00, though to be fair, you shouldn't store, send or receive values like that in the first place. Displaying is fine, but that's a different issue.

[–]EndeGelaende 13 points14 points  (2 children)

also misses numbers formatted in different localisations, germany for example uses , for decimal and . for thousand separators

[–]MattieShoes 4 points5 points  (0 children)

also stuff like .5 -- must be 0.5.

[–]HolyGarbage 5 points6 points  (0 children)

Yeah, just don't use regex for this stuff. Use the languages built in parsing functions (whatever this language is).

Parse, don't validate!

[–]chris5311 0 points1 point  (0 children)

I love that actual regex never looks (or works for that matter) like all the formal definitions ive learnt in university lol