Let’s say there’s a string = “4556 6789”
I want to find all matches of consecutive digits and I use the regex “\d\d” for that. However, it only returns 4 matches (45,56, 67, 89). Expected output is 6 matches (45, 55, 56, 67, 78, 89). How do I achieve that?
bvanb
October 11, 2022, 4:09pm
2
In Javascript, you can use lookaheads with capture groups on String.prototype.matchAll, then convert the resulting iterator with Array.from:
const s = "4556 6789";
matches = Array.from(s.matchAll(/(?=(\d\d))/g), (match) => match[1]);
console.log(matches);
Result:
["45", "55", "56", "67", "78", "89"]
The following link gives a good overview:
E.g. how to capture overlapping pairs of letters from the string `abcde`, i.e. `ab`, `bc`, `cd` and `de`. Spoiler: with lookaheads and lookbehinds.
system
Closed
April 12, 2023, 4:22am
4
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.