Skip to content

Commit 41e843f

Browse files
Improved prefer-character-class rule (#158)
1 parent aca1d21 commit 41e843f

File tree

3 files changed

+707
-81
lines changed

3 files changed

+707
-81
lines changed

docs/rules/prefer-character-class.md

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,15 @@ since: "v0.4.0"
1313

1414
## :book: Rule Details
1515

16-
This rule is aimed to use character classes instead of the disjunction of single element alternatives.
16+
Instead of single-character alternatives (e.g. `(?:a|b|c)`), character classes (e.g. `[abc]`) should be preferred.
17+
18+
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.
19+
20+
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 `a`s, the regex `^[\wa]+b$` will reject a string of _n_ many `a`s in _O(n)_.
21+
22+
### Limitations
23+
24+
This rule might not be able to merge all single-character alternatives.
1725

1826
<eslint-code-block fix>
1927

@@ -22,9 +30,13 @@ This rule is aimed to use character classes instead of the disjunction of single
2230

2331
/* ✓ GOOD */
2432
var foo = /[abc]/
33+
var foo = /(?:a|b)/
2534

2635
/* ✗ BAD */
2736
var foo = /a|b|c/
37+
var foo = /(a|b|c)c/
38+
var foo = /.|\s/
39+
var foo = /(\w|\d)+:/
2840
```
2941

3042
</eslint-code-block>

0 commit comments

Comments
 (0)