regular-expressions.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /**
  2. * @fileoverview Common utils for regular expressions.
  3. * @author Josh Goldberg
  4. * @author Toru Nagashima
  5. */
  6. "use strict";
  7. const { RegExpValidator } = require("@eslint-community/regexpp");
  8. const REGEXPP_LATEST_ECMA_VERSION = 2025;
  9. /**
  10. * Checks if the given regular expression pattern would be valid with the `u` flag.
  11. * @param {number} ecmaVersion ECMAScript version to parse in.
  12. * @param {string} pattern The regular expression pattern to verify.
  13. * @param {"u"|"v"} flag The type of Unicode flag
  14. * @returns {boolean} `true` if the pattern would be valid with the `u` flag.
  15. * `false` if the pattern would be invalid with the `u` flag or the configured
  16. * ecmaVersion doesn't support the `u` flag.
  17. */
  18. function isValidWithUnicodeFlag(ecmaVersion, pattern, flag = "u") {
  19. if (flag === "u" && ecmaVersion <= 5) { // ecmaVersion <= 5 doesn't support the 'u' flag
  20. return false;
  21. }
  22. if (flag === "v" && ecmaVersion <= 2023) {
  23. return false;
  24. }
  25. const validator = new RegExpValidator({
  26. ecmaVersion: Math.min(ecmaVersion, REGEXPP_LATEST_ECMA_VERSION)
  27. });
  28. try {
  29. validator.validatePattern(pattern, void 0, void 0, flag === "u" ? {
  30. unicode: /* uFlag = */ true
  31. } : {
  32. unicodeSets: true
  33. });
  34. } catch {
  35. return false;
  36. }
  37. return true;
  38. }
  39. module.exports = {
  40. isValidWithUnicodeFlag,
  41. REGEXPP_LATEST_ECMA_VERSION
  42. };