Skip to content

Commit 38e6456

Browse files
Improve no-unused-capturing-group docs (#348)
1 parent 4f41661 commit 38e6456

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

docs/rules/no-unused-capturing-group.md

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ since: "v0.6.0"
1414

1515
## :book: Rule Details
1616

17-
This rule aims to optimize regular expressions by replacing unused capturing groups with non-capturing groups.
17+
This rule reports unused capturing groups.
1818

1919
<eslint-code-block fix>
2020

@@ -51,6 +51,26 @@ var index = '2000-12-31'.search(/(\d{4})-(\d{2})-(\d{2})/) // 0
5151

5252
</eslint-code-block>
5353

54+
### Why no unused capturing groups?
55+
56+
Many people use capturing groups instead of non-capturing groups for convenience. `()` is simpler and feels more natural than the cryptic-looking `(?:)`.
57+
58+
However, using capturing groups in place of non-capturing groups also has negative consequences.
59+
60+
#### Performance
61+
62+
Capturing groups are slower than non-capturing groups.
63+
64+
This is by design. Capturing groups (as the name suggests) captured their matched text. The regex engine has to do extra work every time a capturing group is matched compared to a non-capturing group.
65+
66+
#### Code smell
67+
68+
A capturing group is intended to store its matched text so it can later be used, e.g. in text replacements.
69+
70+
That makes a capturing group quite similar to a variable in that its value (the captured text) is stored (by the regex engine) and can be accessed afterward (by the developer). However, if the captured text is not used, then the capturing group will essentially be an unused variable. This makes the regex harder to understand because other developers will have to constantly ask themselves: "Is this a capturing group because the captured text will be used later on in the code, or because `()` is faster to type?"
71+
72+
Using capturing groups only if the captured text is used makes their usage unambiguous and easier for others to understand.
73+
5474
## :wrench: Options
5575

5676
```json

0 commit comments

Comments
 (0)