no-empty-character-class.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * @fileoverview Rule to flag the use of empty character classes in regular expressions
  3. * @author Ian Christian Myers
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Helpers
  8. //------------------------------------------------------------------------------
  9. /*
  10. * plain-English description of the following regexp:
  11. * 0. `^` fix the match at the beginning of the string
  12. * 1. `([^\\[]|\\.|\[([^\\\]]|\\.)+\])*`: regexp contents; 0 or more of the following
  13. * 1.0. `[^\\[]`: any character that's not a `\` or a `[` (anything but escape sequences and character classes)
  14. * 1.1. `\\.`: an escape sequence
  15. * 1.2. `\[([^\\\]]|\\.)+\]`: a character class that isn't empty
  16. * 2. `$`: fix the match at the end of the string
  17. */
  18. const regex = /^([^\\[]|\\.|\[([^\\\]]|\\.)+\])*$/u;
  19. //------------------------------------------------------------------------------
  20. // Rule Definition
  21. //------------------------------------------------------------------------------
  22. /** @type {import('../shared/types').Rule} */
  23. module.exports = {
  24. meta: {
  25. type: "problem",
  26. docs: {
  27. description: "Disallow empty character classes in regular expressions",
  28. recommended: true,
  29. url: "https://eslint.org/docs/rules/no-empty-character-class"
  30. },
  31. schema: [],
  32. messages: {
  33. unexpected: "Empty class."
  34. }
  35. },
  36. create(context) {
  37. return {
  38. "Literal[regex]"(node) {
  39. if (!regex.test(node.regex.pattern)) {
  40. context.report({ node, messageId: "unexpected" });
  41. }
  42. }
  43. };
  44. }
  45. };