diff --git a/src/core/inputs.ts b/src/core/inputs.ts index 37722250..732cd1a5 100644 --- a/src/core/inputs.ts +++ b/src/core/inputs.ts @@ -81,11 +81,11 @@ export function maybe< Inputs extends InputSource[], Value extends string = Join, '', ''>, >(...inputs: Inputs): Input< - IfUnwrapped, + `(?:${Value})?`, MapToGroups, MapToCapturedGroupsArr > { - return createInput(`${wrap(exactly(...inputs))}?`) + return createInput(`(?:${exactly(...inputs)})?`) } /** diff --git a/test/inputs.test.ts b/test/inputs.test.ts index 657ff83d..772cfe80 100644 --- a/test/inputs.test.ts +++ b/test/inputs.test.ts @@ -71,8 +71,7 @@ describe('inputs', () => { expectTypeOf(extractRegExp(input)).toEqualTypeOf<'(?:foo)?'>() const nestedInputWithGroup = maybe(exactly('foo').groupedAs('groupName')) - expectTypeOf(createRegExp(nestedInputWithGroup)).toEqualTypeOf< - MagicRegExp<'/(?foo)?/', 'groupName', ['(?foo)'], never> + expectTypeOf(createRegExp(nestedInputWithGroup)).toEqualTypeOffoo))?/', 'groupName', ['(?foo)'], never> >() const multi = maybe('foo', input.groupedAs('groupName'), 'bar') @@ -81,6 +80,19 @@ describe('inputs', () => { '/\\(\\?:foo\\(\\?\\(\\?:foo\\)\\?\\)bar\\)\\?/', ) expectTypeOf(extractRegExp(multi)).toEqualTypeOf<'(?:foo(?(?:foo)?)bar)?'>() + + const withCaptureGroup = maybe(charIn('-_.').optionally(), oneOrMore(digit).as('number')) + const regexp3 = new RegExp(withCaptureGroup as any) + expect(regexp3).toMatchInlineSnapshot(`/\\(\\?:\\(\\?:\\[\\\\-_\\.\\]\\)\\?\\(\\?\\\\d\\+\\)\\)\\?/`) + const withCaptureGroup2 = exactly( + anyOf('beta', 'dev'), + maybe( + charIn('-_.').optionally(), + oneOrMore(digit).as('number'), + ), + ) + const regexp4 = createRegExp(withCaptureGroup2, ['g', 'i']) + expect(regexp4).toMatchInlineSnapshot(`/\\(\\?:beta\\|dev\\)\\(\\?:\\(\\?:\\[\\\\-_\\.\\]\\)\\?\\(\\?\\\\d\\+\\)\\)\\?/gi`) }) it('oneOrMore', () => { const input = oneOrMore('foo')