Skip to content

Instantly share code, notes, and snippets.

@VladSez
Created December 4, 2023 01:54
Show Gist options
  • Save VladSez/ef6f9293d967223a14cb9aaeefc18e4d to your computer and use it in GitHub Desktop.
Save VladSez/ef6f9293d967223a14cb9aaeefc18e4d to your computer and use it in GitHub Desktop.
greedy js reg ex
// https://stackoverflow.com/questions/49744804/how-to-match-an-overlapping-pattern-multiple-times-using-regexp
// the problem is that by default regexp cant do overlapping patterns
// for example we want: "eighthree" -> ['eight', 'three'] and for "sevenine" -< ['seven', 'nine']
// but with default .match we get "eighthree" -> ['eight'] and for "sevenine" -> ['seven']
const greedyRegex = (str: string) => {
let reg = /one|two|three|four|five|six|seven|eight|nine|\d/g,
next = reg.exec(str),
res = [];
while (next) {
res.push(next[0]);
reg.lastIndex = next.index + 1;
next = reg.exec(str);
}
return res;
};
const res = greedyRegex("sevenineight323") ->  ['seven', 'nine', 'eight', '3', '2', '3']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment