Skip to content
This repository has been archived by the owner on Nov 15, 2024. It is now read-only.

Commit

Permalink
feat: make convertHexDigitsShorthand behind a flag
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Sep 1, 2024
1 parent 75ee5be commit ae8b144
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 23 deletions.
1 change: 1 addition & 0 deletions src/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export function onigurumaToRegexp(
} = syntaxLowering(pattern, {
removePossessiveQuantifier: true,
removeAtomicGroup: true,
convertHexDigitsShorthand: true,
...options,
})

Expand Down
54 changes: 32 additions & 22 deletions src/lowering.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ export interface SyntaxLoweringOptions {
* @default false
*/
removeAtomicGroup?: boolean

/**
* Convert `\h` and `\H` to `[0-9A-Fa-f]` and `[^0-9A-Fa-f]` respectively.
*
* @default false
*/
convertHexDigitsShorthand?: boolean
}

export interface SyntaxLoweringResult {
Expand All @@ -64,6 +71,7 @@ export function syntaxLowering(
preserveFlags = false,
removePossessiveQuantifier = false,
removeAtomicGroup = false,
convertHexDigitsShorthand = false,
} = options

let output = ''
Expand All @@ -89,30 +97,32 @@ export function syntaxLowering(

// Escape sequences
if (char === '\\') {
// Expand \h shorthands
if (input[i + 1] === 'h') {
const body = `0-9A-Fa-f`
if (head === '[') {
output += body
}
else {
output += `[${body}]`
}
i += 2
continue
}
if (input[i + 1] === 'H') {
if (head === '[') {
throw new RegExpConversionError(
'Expending \\H in character class is not supported',
{ pattern: input, converted: output, cursor: i },
)
// Expand \h and \H
if (convertHexDigitsShorthand) {
if (input[i + 1] === 'h') {
const body = `0-9A-Fa-f`
if (head === '[') {
output += body
}
else {
output += `[${body}]`
}
i += 2
continue
}
else {
output += `[^0-9A-Fa-f]`
if (input[i + 1] === 'H') {
if (head === '[') {
throw new RegExpConversionError(
'Expending \\H in character class is not supported',
{ pattern: input, converted: output, cursor: i },
)
}
else {
output += `[^0-9A-Fa-f]`
}
i += 2
continue
}
i += 2
continue
}
output += char + input[i + 1]
i += 2
Expand Down
2 changes: 1 addition & 1 deletion test/lowering.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ it('lowering mixed flags', () => {
})

it('lowering \\h', () => {
expect(syntaxLowering('(?x)\\h [\\h\\w] \\H'))
expect(syntaxLowering('(?x)\\h [\\h\\w] \\H', { convertHexDigitsShorthand: true }))
.toMatchInlineSnapshot(`
{
"flags": "",
Expand Down

0 comments on commit ae8b144

Please sign in to comment.