Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cancerberoSgx/6e2eccf853e7cbe430de7ec5af0764cc to your computer and use it in GitHub Desktop.
Save cancerberoSgx/6e2eccf853e7cbe430de7ec5af0764cc to your computer and use it in GitHub Desktop.
exec global regex and get each group index

exec global regex and get each group index

is not direct way in js to iterate a global regex and obtain the location of each group match in the input. This is kind of straight forward solution using indexOf and sum

A Pen by Sebastián Gurin on CodePen.

License.

!function () {
const regex = /\/\*\*\*@\s*([^@]+)\s*(@\*\*\*\/)/gim
const exampleThatMatch = `
/***@
debug.print('hello editor, simpleNode kind is ' +
arg.simpleNode.getKindName())
@***/
const a = 1 //user
/***@
debug.print(arg.simpleNode.getParent().getKindName())
@***/
`
const text = exampleThatMatch
function exec(r, s) {
function indexOfGroup(match, n) {
var ix = match.index;
for (var i = 1; i < n; i++)
ix += match[i].length;
return ix;
}
let result
let lastMatchIndex = 0
const matches = []
while ((result = regex.exec(text))) {
const match = []
lastMatchIndex = text.indexOf(result[0], lastMatchIndex)
let relIndex = 0
for (let i = 1; i < result.length; i++) {
relIndex = text.indexOf(result[i], relIndex)
match.push({ value: result[i], start: relIndex, end: relIndex + result[i].length })
}
matches.push(match)
}
return matches
}
const groupsWithIndex = exec(regex, text)
console.log({RESULT: groupsWithIndex })
// now test - let's remove everything else but matched groups
let frag = '' , sep = '\n#######\n'
groupsWithIndex.forEach(match => match.forEach(group => {
frag += text.substring(group.start, group.end) + sep
}))
console.log('The following are only the matched groups usign the result and text.substring just to verify it works OK:', '\n'+sep)
console.log(frag)
}()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment