简体   繁体   中英

JavaScript regex: why match number with trailing decimal?

I have been reading JavaScript: The Good Parts by Douglas Crockford. In the section on regular expressions, there is the following regex to parse a number:

var parse_number = /^-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?$/i;

This regex is pretty straightforward to begin with, and Crockford breaks it down so that almost every aspect is very clear. However, there is one aspect that is not fully explained, and which I cannot figure out:

(?:\.\d*)?

His explanation, which I do understand, is:

The (?:... )? indicates an optional noncapturing group...The group will match a decimal point followed by zero or more digits.

The part that confuses me, and which is not explained, is why zero or more digits rather than one or more digits , ie, why use \\d* instead of \\d+ in this case? My intuition, which was confirmed through .test ing, is that the parse_number pattern described above will match not only strings like '1.0' - which you would likely want to match - but will also match strings like '1.' with a trailing decimal, which I cannot think of a use case for.

I assume there is a very good reason for using:

(?:\.\d*)?

instead of:

(?:\.\d+)?

but what might that reason be?

To match the JavaScript NumericLiteral syntax production , which allows for a trailing . with no digits after it. It's called out here:

DecimalLiteral ::

DecimalIntegerLiteral . DecimalDigits opt ExponentPart opt

Note how both the DecimalDigits and ExponentPart of that are optional.

This is entirely valid JavaScript:

 var a = 42.; // -------^ console.log(a); // 42 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM