Home > Web Front-end > JS Tutorial > Why Does JavaScript's `match()` Method Only Find Non-Overlapping Regular Expression Matches?

Why Does JavaScript's `match()` Method Only Find Non-Overlapping Regular Expression Matches?

Mary-Kate Olsen
Release: 2024-12-19 17:50:13
Original
922 people have browsed it

Why Does JavaScript's `match()` Method Only Find Non-Overlapping Regular Expression Matches?

Overlapping Matches in Regular Expressions

In regular expressions, the match method with the g (global) flag typically matches and captures only non-overlapping substrings. Consider the following example:

const text = "12345";
const regex = /\d{3}/g;
const matches = text.match(regex);
Copy after login

In this case, we would expect to get three matches: "123", "234", and "345". However, using the match method, we only obtain "123".

Why Only One Match?

The match method consumes the matched substring and advances its index. After capturing "123", the index is now past the third character, leaving only "45" for potential matching. Since this remaining portion does not meet the d{3} pattern, no further matches are found.

Addressing Overlapping Matches

To capture overlapping matches, we need to use a different technique employed in some regex flavors such as .Net, Python, PHP, and Ruby. This technique involves using a zero-width assertion (positive lookahead with a capturing group) to test all positions within the input string. The RegExp.lastIndex property is manually incremented to advance through the string without infinite looping.

For example, using the matchAll method:

const re = /(?=(\d{3}))/g;
const matches = Array.from('12345'.matchAll(re));
console.log(matches.map(match => match[1])); // ["123", "234", "345"]
Copy after login

This approach captures all three overlapping matches as desired. Remember, the technique is only supported in certain regex flavors.

The above is the detailed content of Why Does JavaScript's `match()` Method Only Find Non-Overlapping Regular Expression Matches?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template