Skip to content

Instantly share code, notes, and snippets.

@lmmx lmmx/regex_multi_match.js
Last active Aug 29, 2015

Embed
What would you like to do?
Regex multiple matching with exec via http://stackoverflow.com/a/2295943/2668831
myre = /]\(/g
mystr = 'hello ]( world ]( i ]( said ]('
while ((match = myre.exec(mystr)) != null) {
console.log(myre.lastIndex)
}
/*
8
17
22
30
*/
while ((match = myre.exec(mystr)) != null) {
console.log(match.index + match[0].length)
}
/*
8
17
22
30
*/
// mystr.length
// 30
/* Note that if assigning a value, repeated overwriting lets you use the last output of the loop
- can be handy, e.g. find the definitive separator in a markdown link: */
var mylink = "![hello ]( world ]( i ]( said ](https://gist.github.com)"
// strip off ![ and ), so start from character 2 and end 3 characters shorter than length
var link_inner = mylink.substr(2, mylink.length - 3);
while ((match = myre.exec(link_inner)) != null) {
var link_sep = myre.lastIndex;
}
matchstring = '](' // for reference
var link_alt = link_inner.substring(0, link_sep - matchstring.length);
// "hello ]( world ]( i ]( said "
var link_href = link_inner.substring(link_sep);
// "https://gist.github.com"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.