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

JavaScript match方法非穷尽匹配问题:为何匹配结果为2而非3?

Does JavaScript's match() method have a non-exhaustive matching issue? Why does console.log("1010101".match(/101/g)); return 2 instead of 3?

Great question—this is a super common point of confusion with regex global matching in JavaScript, so let’s break it down clearly.

First, let’s confirm what’s happening: when you run "1010101".match(/101/g), the result is ["101", "101"] instead of the 3 matches you might expect. This isn’t a flaw in the match() method itself—it’s how standard global regex matching works in JavaScript (and most other programming languages).

Why only 2 matches?

Let’s walk through the matching process step by step with the string "1010101" (indexes 0 to 6):

  1. First match: The regex starts at index 0, finds the sequence 101 covering indexes 0-2. Once a match is found, the regex engine doesn’t start the next check right after the first character of the match—it jumps to the end of the current match (index 3).
  2. Second match: Starting at index 3, the next character is 0, which doesn’t match the regex’s starting 1. The engine moves forward to index 4, finds another 101 covering indexes 4-6. Again, it jumps to the end of this match (index 7), which is beyond the string length.
  3. No third match: The engine never checks the overlapping sequence starting at index 2 (101 covering 2-4) because it skipped past that position after the first match.

This is called non-overlapping matching, which is the default behavior for global regex searches.

How to get overlapping matches?

If you want to capture all overlapping instances of 101, you need to use a zero-width positive lookahead assertion to avoid "consuming" the characters in the match. Here’s how:

const str = "1010101";
const regex = /(?=(101))/g;
const matches = [];
let match;

while ((match = regex.exec(str)) !== null) {
  matches.push(match[1]);
}

console.log(matches); // Output: ["101", "101", "101"]

The (?=...) lookahead checks if 101 exists starting at the current position, but doesn’t move the regex engine’s pointer past those characters. This lets the engine check every possible starting position, including overlapping ones.

To wrap up

The match() method doesn’t have a non-exhaustive matching issue—it’s just following the standard rules of regex global matching. The "missing" third match is a result of non-overlapping behavior, not a bug.

内容的提问来源于stack exchange,提问作者Digadogup

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:33:00