Home >Web Front-end >JS Tutorial >How Can I Use Regex to Find Overlapping Matches in a String?

How Can I Use Regex to Find Overlapping Matches in a String?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-06 05:19:10953browse

How Can I Use Regex to Find Overlapping Matches in a String?

Overlapping String Matching with Regex

In the string "12345," applying ".match(/d{3}/g)" should ideally return three matches: "123," "234," and "345." However, only one match ("123") is obtained.

Reason:

The global flag "g" in the regex consumes three digits and advances the index to the position after the first match. This means that when the regex tries to match the next substring, the index is already at position 3, effectively skipping the remaining overlapping matches.

Solution: Zero-Width Assertion

A zero-width assertion, specifically a positive lookahead with a capturing group, can be employed to match all positions within the input string. This technique involves:

  • Testing every position using the lookahead assertion.
  • Manually advancing the RegExp.lastIndex property to avoid an infinite loop.

Example in JavaScript:

var re = /(?=(\d{3}))/g;
console.log(Array.from('12345'.matchAll(re), x => x[1]));

The above is the detailed content of How Can I Use Regex to Find Overlapping Matches in a String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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