Skip to content

Commit

Permalink
Fix es.regexp.constructor - handleNCG - consider captured groups in…
Browse files Browse the repository at this point in the history
…side non-capturing groups (#1352)

Co-authored-by: alazarev <alazarev@megaputer.ru>
  • Loading branch information
Ulop and alazarev committed Jul 2, 2024
1 parent a56fd5b commit 6b83ac1
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
6 changes: 4 additions & 2 deletions packages/core-js/modules/es.regexp.constructor.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,13 @@ var handleNCG = function (string) {
brackets = true;
break;
case chr === '(':
if (exec(IS_NCG, stringSlice(string, index + 1))) {
result += chr;
if (stringSlice(string, index + 1, index + 3) === '?:') { // avoid groupid increment in non-capturing group
continue;
} else if (exec(IS_NCG, stringSlice(string, index + 1))) {
index += 2;
ncg = true;
}
result += chr;
groupid++;
continue;
case chr === '>' && ncg:
Expand Down
9 changes: 9 additions & 0 deletions tests/unit-global/es.regexp.constructor.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,15 @@ if (DESCRIPTORS) {
const { groups } = RegExp('foo:(?<foo>\\w+),bar:(?<bar>\\w+)').exec('foo:abc,bar:def');
assert.same(getPrototypeOf(groups), null, 'null prototype');
assert.deepEqual(groups, { foo: 'abc', bar: 'def' }, 'NCG #3');
// eslint-disable-next-line regexp/no-useless-non-capturing-group -- required for testing
const { groups: nonCaptured, length } = RegExp('foo:(?:value=(?<foo>\\w+)),bar:(?:value=(?<bar>\\w+))').exec('foo:value=abc,bar:value=def');
assert.deepEqual(nonCaptured, { foo: 'abc', bar: 'def' }, 'NCG #4');
assert.same(length, 3, 'incorrect number of matched entries #1');

// eslint-disable-next-line regexp/no-unused-capturing-group -- required for testing
const { groups: skipBar } = RegExp('foo:(?<foo>\\w+),bar:(\\w+),buz:(?<buz>\\w+)').exec('foo:abc,bar:def,buz:ghi');
assert.deepEqual(skipBar, { foo: 'abc', buz: 'ghi' }, 'NCG #5');

// fails in Safari
// assert.same(Object.getPrototypeOf(groups), null, 'NCG #4');
assert.same('foo:abc,bar:def'.replace(RegExp('foo:(?<foo>\\w+),bar:(?<bar>\\w+)'), '$<bar>,$<foo>'), 'def,abc', 'replace #1');
Expand Down

0 comments on commit 6b83ac1

Please sign in to comment.