Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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++;
Copy link
Owner

@zloirock zloirock Jul 1, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It will break cases like

RegExp('foo:(?<foo>\\w+),bar:(\\w+),buz:(?<buz>\\w+)').exec('foo:abc,bar:def,buz:ghi').groups.buz

since here is a non-named group.

Could you fix it and add a couple of cases like that to the tests?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, you are right. Changes like these really break some cases.

I added an additional check to a non-capturing group after '(' character and revert the previous changes.
Also extended regexp constructor test with your example.

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