简体   繁体   English

JavaScript正则表达式:为什么将数字与尾随十进制相匹配?

[英]JavaScript regex: why match number with trailing decimal?

I have been reading JavaScript: The Good Parts by Douglas Crockford. 我一直在阅读Douglas Crockford的JavaScript:The Good Parts 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. 这个正则表达式一开始就非常简单,Crockford对其进行了分解,因此几乎每个方面都非常清楚。 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? 让我感到困惑的部分(未解释)是为什么 零个或多个数字而不是一个或多个数字 ,即为什么在这种情况下使用\\d*而不是\\d+ 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.' 我的直觉(通过.test确认)是,上述parse_number模式不仅将匹配'1.0'这样'1.0'字符串(您可能希望匹配),还将匹配诸如'1.'字符串'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 . 为了匹配JavaScript NumericLiteral语法生成 ,该语法生成允许尾随. with no digits after it. 后面没有数字。 It's called out here: 它在这里被呼出:

DecimalLiteral :: DecimalLiteral ::

DecimalIntegerLiteral . DecimalIntegerLiteral . DecimalDigits opt ExponentPart opt DecimalDigits opt ExponentPart opt

Note how both the DecimalDigits and ExponentPart of that are optional. 请注意, DecimalDigitsExponentPart两者是可选的。

This is entirely valid JavaScript: 这是完全有效的JavaScript:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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