regexEmptyAlternatives
Reports empty alternatives in regular expressions that may indicate a mistake.
✅ This rule is included in the tslogicalandlogicalStrictpresets.
Empty alternatives in regular expressions match zero characters. While sometimes intentional, they often indicate a mistake such as a typo or incomplete pattern.
Examples
Section titled “Examples”Empty Alternative at End
Section titled “Empty Alternative at End”An empty alternative at the end of a group or pattern.
const pattern = /a|/;const pattern = /a?/;Empty Alternative at Start
Section titled “Empty Alternative at Start”An empty alternative at the start of a group or pattern.
const pattern = /|a/;const pattern = /a?/;Empty Alternative in Groups
Section titled “Empty Alternative in Groups”Empty alternatives in capturing and non-capturing groups.
const pattern = /(a|)/;const pattern = /(a)?/;RegExp Constructor
Section titled “RegExp Constructor”The rule also checks regex patterns in RegExp constructor calls.
const pattern = new RegExp("a|b|");const pattern = new RegExp("a|b");Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you intentionally use empty alternatives to make a pattern optional and prefer this style over quantifiers, you might prefer to disable this rule.
Some developers find (a|) more readable than a? for complex patterns.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- ESLint:
regexp/no-empty-alternative
Made with ❤️🔥 in Boston by
Josh Goldberg and contributors.