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));
})
{
"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.: