Created
December 4, 2023 01:54
-
-
Save VladSez/ef6f9293d967223a14cb9aaeefc18e4d to your computer and use it in GitHub Desktop.
greedy js reg ex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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