Skip to content
Open
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
4 changes: 2 additions & 2 deletions src/core/inputs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,11 @@ export function maybe<
Inputs extends InputSource[],
Value extends string = Join<MapToValues<Inputs>, '', ''>,
>(...inputs: Inputs): Input<
IfUnwrapped<Value, `(?:${Value})?`, `${Value}?`>,
`(?:${Value})?`,
MapToGroups<Inputs>,
MapToCapturedGroupsArr<Inputs>
> {
return createInput(`${wrap(exactly(...inputs))}?`)
return createInput(`(?:${exactly(...inputs)})?`)
}

/**
Expand Down
16 changes: 14 additions & 2 deletions test/inputs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,7 @@ describe('inputs', () => {
expectTypeOf(extractRegExp(input)).toEqualTypeOf<'(?:foo)?'>()

const nestedInputWithGroup = maybe(exactly('foo').groupedAs('groupName'))
expectTypeOf(createRegExp(nestedInputWithGroup)).toEqualTypeOf<
MagicRegExp<'/(?<groupName>foo)?/', 'groupName', ['(?<groupName>foo)'], never>
expectTypeOf(createRegExp(nestedInputWithGroup)).toEqualTypeOf<MagicRegExp<'/(?:(?<groupName>foo))?/', 'groupName', ['(?<groupName>foo)'], never>
>()

const multi = maybe('foo', input.groupedAs('groupName'), 'bar')
Expand All @@ -81,6 +80,19 @@ describe('inputs', () => {
'/\\(\\?:foo\\(\\?<groupName>\\(\\?:foo\\)\\?\\)bar\\)\\?/',
)
expectTypeOf(extractRegExp(multi)).toEqualTypeOf<'(?:foo(?<groupName>(?:foo)?)bar)?'>()

const withCaptureGroup = maybe(charIn('-_.').optionally(), oneOrMore(digit).as('number'))
const regexp3 = new RegExp(withCaptureGroup as any)
expect(regexp3).toMatchInlineSnapshot(`/\\(\\?:\\(\\?:\\[\\\\-_\\.\\]\\)\\?\\(\\?<number>\\\\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\\)\\(\\?:\\(\\?:\\[\\\\-_\\.\\]\\)\\?\\(\\?<number>\\\\d\\+\\)\\)\\?/gi`)
})
it('oneOrMore', () => {
const input = oneOrMore('foo')
Expand Down