正则表达式/\B(?=(\d{3})+(?!\d))/g的解析与用途咨询
正则表达式/\B(?=(\d{3})+(?!\d))/g的解析与用途咨询
Hey there! Let's break down this regex piece by piece so you can see exactly what it's doing—it's actually a super common trick for adding thousand separators to numbers, like turning 123456 into 1,234,567.
Let's go through each part of the regex:
\B: This matches a non-word boundary. Unlike\b(which targets edges between word and non-word characters),\Bfocuses on positions between two word characters (or two non-word characters). Here, it ensures we never add a comma at the very start of a number (so we won't end up with,123for the number 123).(?=...): This is a positive lookahead—it checks that the text right after the current position matches what's inside the parentheses, but it doesn't "use up" those characters. In short, we're just targeting a position, not replacing the digits themselves.(\d{3})+: This looks for one or more groups of exactly 3 digits.\d{3}grabs 3 consecutive numbers, and the+means this group can repeat (so 3, 6, 9, etc., digits in total).(?!\d): This is a negative lookahead—it makes sure that after those groups of 3 digits, there are no extra digits left. This stops us from adding commas in the middle of an incomplete 3-digit group (like in1234, we wouldn't add a comma after the1because only 2 digits are left, not a full 3)./g: The global flag—this tells the regex engine to find all matching positions in the string, not just the first one. That's why we get multiple commas for longer numbers (like123,456,789instead of just123,456789).
Put it all together: this regex finds every position in a number where, if you look ahead, you see one or more full 3-digit groups followed by the end of the number. Then the replace method drops a comma into each of those positions.
For a quick example:
- Input number:
1234567 - After running the replace:
1,234,567
备注:内容来源于stack exchange,提问作者Nate Brown
相关产品推荐
相关产品推荐

