Skip to content

Latest commit

 

History

History
74 lines (50 loc) · 2.19 KB

prefer-character-class.md

File metadata and controls

74 lines (50 loc) · 2.19 KB
pageClass sidebarDepth title description since
rule-details
0
regexp/prefer-character-class
enforce using character class
v0.4.0

regexp/prefer-character-class

💼 This rule is enabled in the ✅ plugin:regexp/recommended config.

🔧 This rule is automatically fixable by the --fix CLI option.

enforce using character class

📖 Rule Details

Instead of single-character alternatives (e.g. (?:a|b|c)), character classes (e.g. [abc]) should be preferred.

The main reason for doing this is performance. Character classes don't require backtracking and are heavily optimized by the regex engine. On the other hand, alternatives are usually quite tricky to optimize.

Character classes are also safer than alternatives because they don't require backtracking. While ^(?:\w|a)+b$ will take O(2^n) time to reject a string of n many as, the regex ^[\wa]+b$ will reject a string of n many as in O(n).

Limitations

This rule might not be able to merge all single-character alternatives.

/* eslint regexp/prefer-character-class: "error" */

/* ✓ GOOD */
var foo = /[abc]/
var foo = /(?:a|b)/

/* ✗ BAD */
var foo = /a|b|c/
var foo = /(a|b|c)c/
var foo = /.|\s/
var foo = /(\w|\d)+:/

🔧 Options

{
  "regexp/prefer-character-class": [
    "error",
    {
        "minAlternatives": 3
    }
  ]
}

minAlternatives: integer

This number controls how many character alternatives have to be present for them to be merged. By default, there need to be at least 3 alternatives.

Note that this option does not affect character alternatives where the characters overlap. These alternatives will always be merged to prevent excessive backtracking.

🚀 Version

This rule was introduced in eslint-plugin-regexp v0.4.0

🔍 Implementation