Home > database >  Start and end positions of the *groups* of a Javascript stdlib regex match
Start and end positions of the *groups* of a Javascript stdlib regex match

Time:08-27

Is it possible to get the start and end positions of the groups of a Javascript regex match?

NOTE: 'groups'.

(It's weird that I can't find information about this. Which suggests that it isn't available. Which is weird. Java and Python seem to have this capability.)

CodePudding user response:

This information is in the indices property of the return value of RegExp.exec() (and other methods that are defined to return the same type of result). The regular expression has to have the d flag to enable returning this. Numbered groups are in the indices array, named groups are properties of the indices.groups object.

// Match "quick brown" followed by "jumps", ignoring characters in between
// Remember "brown" and "jumps"
// Ignore case
const re = /quick\s(?<color>brown). ?(jumps)/igd;
const result = re.exec('The Quick Brown Fox Jumps Over The Lazy Dog');

console.log(result.indices);
console.log(result.indices.groups);

  • Related