正则表达式从右到左阅读 [英] Regex reads from right to left
问题描述
我正在寻找一个简短的代码,可以将逗号括在一组数字中,直到我来到这个网站。
I was looking for a short code that can put commas in set of numbers until I came to this site.
代码:
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
工作真的很棒。有这个例子的数字集:
Works really great. Having this example set of number:
addCommas('83475934.89');
将返回83,475,934.89
,但是当我读了代码,我希望它返回 8,3,4,7,5,934.89
但这个网站解释说
Will return "83,475,934.89"
, but when I read the code, I expect it to return 8,3,4,7,5,934.89
but this sites explains that
\d +
与 \d {3}
组合将匹配a一组3个数字,前面是任意数量的数字。这会欺骗搜索从右到左替换。
\d+
in combination with\d{3}
will match a group of 3 numbers preceded by any amount of numbers. This tricks the search into replacing from right to left.
我很困惑。
此代码如何从右到左阅读?另外, $ 1
和 $ 2
是什么意思?
And I get so confused.
How does this code read from right to left? Plus, what does $1
and $2
mean?
推荐答案
它从右到左匹配,因为它使用贪婪模式匹配。这意味着它首先找到所有数字(\d +),然后尝试找到\d {3}。在数字2421567.56中,例如,它将首先匹配数字直到'。' - 2431567 - 然后向后工作以匹配正则表达式的下一部分中的下三个数字(567)。它在$ 1和$ 2变量之间添加逗号的循环中执行此操作。
It matches from right to left because it uses greedy pattern matching. This means that it first finds all the digits (the \d+), then tries to find the \d{3}. In the number 2421567.56, for example it would first match the digits up until the '.' - 2431567 - then works backwards to match the next 3 digits (567) in the next part of the regex. It does this in a loop adding a comma between the $1 and $2 variables.
$表示在正则表达式中使用括号形成的匹配组,例如(\d +)= $ 1和(\d {3})= $ 2。这样,它可以轻松地在它们之间添加字符。
The $'s represent matching groups formed in the regex with parentheses e.g. the (\d+) = $1 and (\d{3}) = $2. In this way it can easily add characters between them.
在下一次迭代中,贪婪匹配在新创建的逗号处停止,并继续直到它不匹配> 3位数。
In the next iteration, the greedy matching stops at the newly created comma instead, and it continues until it can't match > 3 digits.
这篇关于正则表达式从右到左阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!