With regular expressions syntax, it’s possible to express the same thing in many ways. For example, to match a two-digit number, one could write
[0-9]{2,2}
or \d{2}
. Latter is not only shorter in terms of expression length, but also easier to read and thus to maintain.
This rule recommends to replace some bulky quantifiers and character classes with more concise equivalents:
-
\d
for [0-9]
and \D
for [^0-9]
-
\w
for [A-Za-z0-9_]
and \W
for [^A-Za-z0-9_]
-
.
for character classes matching everything (e.g. [\w\W]
, [\d\D]
, or [\s\S]
with
s
flag)
-
x?
for x{0,1}
, x*
for x{0,}
, x+
for x{1,}
, x{N}
for
x{N,N}
Noncompliant Code Example
"[0-9]" // Noncompliant - same as "\\d"
"[^0-9]" // Noncompliant - same as "\\D"
"[A-Za-z0-9_]" // Noncompliant - same as "\\w"
"[\\w\\W]" // Noncompliant - same as "."
"a{0,}" // Noncompliant - same as "a*"
Compliant Solution
"\\d"
"\\D"
"\\w"
"."
"a*"