regexCharacterClassSetOperations
Reports lookarounds that can be replaced with character class set operations.
✅ This rule is included in the tsstylisticandstylisticStrictpresets.
Regular expressions with the v flag have access to character class set operations like intersection (&&) and subtraction (--).
These are more readable and performant than using lookarounds to achieve the same effect.
Examples
Section titled “Examples”// Negative lookahead can be subtractionconst const pattern: RegExp
pattern = /(?!\d)\w/v;Error ts(1501) ― // Positive lookbehind can be intersectionconst const pattern: RegExp
pattern = /\w(?<=\d)/v;Error ts(1501) ― // Positive lookahead can be intersectionconst const pattern: RegExp
pattern = /(?=\d)\w/v;Error ts(1501) ― // Use subtraction instead of negative lookaheadconst const pattern: RegExp
pattern = /[\w--\d]/v;Error ts(1501) ― // Use intersection instead of positive lookbehindconst const pattern: RegExp
pattern = /[\w&&\d]/v;Error ts(1501) ― // Use intersection instead of positive lookaheadconst const pattern: RegExp
pattern = /[\w&&\d]/v;Error ts(1501) ― // Lookarounds without the v flag are validconst const pattern: RegExp
pattern = /(?!\d)\w/;// Complex lookarounds cannot be convertedconst const pattern: RegExp
pattern = /(?!abc)\w/v;Error ts(1501) ― Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you prefer the explicit semantics of lookarounds over set operations, this rule might not be for you.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- ESLint:
regexp/prefer-set-operation
Made with ❤️🔥 around the world by
the Flint team and contributors.