You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

正则表达式/\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), \B focuses 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 ,123 for 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 in 1234, we wouldn't add a comma after the 1 because 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 (like 123,456,789 instead of just 123,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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 18:08:13