Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve S5869 description mentioning special characters escapes #4156

Closed
gabriel-vivas-sonarsource opened this issue Sep 12, 2023 · 0 comments · Fixed by #4331
Closed

Improve S5869 description mentioning special characters escapes #4156

gabriel-vivas-sonarsource opened this issue Sep 12, 2023 · 0 comments · Fixed by #4331
Assignees
Milestone

Comments

@gabriel-vivas-sonarsource
Copy link

Label Description
Rule S5869 "Duplicate regex chars"
Subject Add clarification in the description about special character escapes
Community https://community.sonarsource.com/t/false-positive-for-typescript-s5869-duplicate-regex-chars-with-special-character-classes/98995

Explanation

A community member opened a thread for rule S5869 (duplicate chars in regex character class) thinking there was a false positive:

const result = /^[\r\n\s\t]+/gm.exec(source);

However, the rule is working as expected, since \s includes \r, \n, \t, among other invisible characters.
So the regex could be written this way:

const result = /^\s+/gm.exec(source);

This means the rule is accurate, however, it was not obvious from the rule description.

Understandably, users would expect to see an explicit duplicate character since this is the first example provided:

/[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)

Suggestion

We could improve the rule description to mention that there are special escape characters that work like character classes:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class_escape

  • We should mention: \d, \D, \s, \S, \w, \W, since some developers might not be familiar with them
  • We could consider adding a specific example for \s, like in the case reported by the user in the community thread.

I think this will make the rule more useful, and help with the learning aspect.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants