Skip to content

Commit

Permalink
Flag x: Clean up token separators in more cases
Browse files Browse the repository at this point in the history
  • Loading branch information
slevithan committed Jul 22, 2024
1 parent e36c7b1 commit a73131e
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 9 deletions.
14 changes: 8 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,15 +163,17 @@ The following example illustrates how subroutines and backreferences differ:
```js
// A backreference with \k<name>
regex`(?<prefix>sens|respons)e\ and\ \k<prefix>ibility`
/* Matches: - 'sense and sensibility'
- 'response and responsibility' */
/* Matches:
- 'sense and sensibility'
- 'response and responsibility' */

// A subroutine with \g<name>
regex`(?<prefix>sens|respons)e\ and\ \g<prefix>ibility`
/* Matches: - 'sense and sensibility'
- 'sense and responsibility'
- 'response and sensibility'
- 'response and responsibility' */
/* Matches:
- 'sense and sensibility'
- 'sense and responsibility'
- 'response and sensibility'
- 'response and responsibility' */
```

Subroutines go beyond the composition benefits of [interpolation](#-interpolation). Apart from the obvious difference that they don't require variables to be defined outside of the regex, they also don't simply insert the referenced subpattern.
Expand Down
4 changes: 4 additions & 0 deletions spec/flag-x-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,10 @@ describe('flag x', () => {
expect(() => regex`(?< n >)`).toThrow();
expect(() => regex`(?<n>)\k< n >`).toThrow();
});

it('should avoid adding token separators when it is safe to do so', () => {
expect(regex` ^ (?! a \s b . c | d [] e ) $ `.source).toBe('^(?!a\\sb.c|d[]e)$');
});
});

describe('in character class context', () => {
Expand Down
6 changes: 3 additions & 3 deletions src/flag-x.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,11 +139,11 @@ export function rakePostprocessor(expression) {
// No need for separators at:
// - The beginning, if not followed by a quantifier.
// - The end.
// - Before one of `()|$\`.
// - After one of `()|>^`, `(?:`, or a lookaround opening.
// - Before one of `()|.[$\`.
// - After one of `()|.]^>`, `\[bBdDfnrsStvwW]`, `(?:`, or a lookaround opening.
expression = replaceUnescaped(
expression,
String.raw`^${sep}(?![?*+{])|${sep}$|${sep}(?=[()|$\\])|(?<=[()|>^]|\(\?(?:[:=!]|<[=!]))${sep}`,
String.raw`^${sep}(?![?*+{])|${sep}$|${sep}(?=[()|.[$\\])|(?<=[()|.\]^>]|\\[bBdDfnrsStvwW]|\(\?(?:[:=!]|<[=!]))${sep}`,
'',
Context.DEFAULT
);
Expand Down

0 comments on commit a73131e

Please sign in to comment.