Skip to content

Commit

Permalink
Improve S5869 (duplicates-in-character-class): Mention character cl…
Browse files Browse the repository at this point in the history
…ass escapes (#4331)
  • Loading branch information
yassin-kammoun-sonarsource authored Oct 31, 2023
1 parent eabc894 commit be2ebd9
Showing 1 changed file with 21 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,31 @@ <h2>Why is this an issue?</h2>
mistake is trying to use a range like <code>[0-99]</code> to match numbers of up to two digits, when in fact it is equivalent to <code>[0-9]</code>.
Another common cause is forgetting to escape the <code>-</code> character, creating an unintended range that overlaps with other characters in the
character class.</p>
<h3>Noncompliant code example</h3>
<pre>
<p>Character ranges can also create duplicates when used with character class escapes. These are a type of escape sequence used in regular expressions
to represent a specific set of characters. They are denoted by a backslash followed by a specific letter, such as <code>\d</code> for digits,
<code>\w</code> for word characters, or <code>\s</code> for whitespace characters. For example, the character class escape <code>\d</code> is
equivalent to the character range <code>[0-9]</code>, and the escape <code>\w</code> is equivalent to <code>[a-zA-Z0-9_]</code>.</p>
<h2>How to fix it</h2>
<p>Remove the extra character, character range, or character class escape.</p>
<h3>Code examples</h3>
<h4>Noncompliant code example</h4>
<pre data-diff-id="1" data-diff-type="noncompliant">
/[0-99]/ // Noncompliant, this won't actually match strings with two digits
/[0-9.-_]/ // Noncompliant, .-_ is a range that already contains 0-9 (as well as various other characters such as capital letters)
/[a-z0-9\d]/ // Noncompliant, \d matches a digit and is equivalent to [0-9]
</pre>
<h3>Compliant solution</h3>
<pre>
<h4>Compliant solution</h4>
<pre data-diff-id="1" data-diff-type="compliant">
/[0-9]{1,2}/
/[0-9.\-_]/
/[a-z\d]/
</pre>
<h2>Resources</h2>
<h3>Documentation</h3>
<ul>
<li> MDN web docs - <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes">Character
classes</a> </li>
<li> MDN web docs - <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class_escape">Character
class escape</a> </li>
</ul>

0 comments on commit be2ebd9

Please sign in to comment.