1

Terms

Matched pattern

indicate all matched portions of the input string, which all reside inside the match array. These are all instances of your pattern inside the input string.

Matched groups

indicate all groups to catch, defined in the RegEx pattern. (The patterns inside parentheses, like so: /format_(.?)/g, where (.?) would be a matched group.) These reside within matched patterns.

We can determine the offset of the matched pattern easily, for example by using replace() :

// offset of the matched pattern is : arguments[arguments.length - 2]
'lorem ipsum dolor sit amet'.replace(/ip(\w+)[ ]/g, function() {
     console.log(JSON.stringify(arguments, undefined, 2));
})
The result of execution will be :
{
  "0": "ipsum ",
  "1": "sum", 
  "2": 6,
  "3": "lorem ipsum dolor sit amet"
}

So, how to programmatically determine the offset of the matched group instead of the whole matched pattern?

In this case, the offset of "sum" in above example, which is 8.

Both of the text and regex are user input. So, hardcoded way to generate the offset of the group is not an option.

By the way, regex101.com can generates these offsets fairly fast, So there is must be away to do this.: enter image description here

Donovan P
  • 591
  • 5
  • 9
  • 3
    https://stackoverflow.com/questions/15934353/get-index-of-each-capture-in-a-javascript-regex – emptyhua Oct 09 '21 at 09:55
  • Also, [this code](https://jsfiddle.net/wiktor_stribizew/s72qvdo8/) shows some sort of workaround. Note the number of groups is always constant, so you can pass them as arguments into the callback function. – Wiktor Stribiżew Oct 09 '21 at 10:52

0 Answers0