此regex方言不支持条件



在我的typescript文件中,我想使用包含条件表达式的正则表达式,但我的IDE使用条件表达式报告来强调RegEx的部分:"此正则表达式方言中不支持条件语句";。如何启用支持条件正则表达式的方言?

export const phoneRegEx = /^+?d*s?(?(?(?<=()d+)s?d+(-|s|.)?(?:1?d)*|(.|s|-)?(2?d)*)$/g;

我的package.json文件:

{
"private": true,
"scripts": {
"dev": "npm run development",
"development": "mix",
"watch": "mix watch",
"watch-poll": "mix watch -- --watch-options-poll=1000",
"hot": "mix watch --hot",
"prod": "npm run production",
"production": "mix --production"
},
"devDependencies": {
"@babel/preset-react": "^7.13.13",
"@tsconfig/create-react-app": "^1.0.2",
"@types/js-cookie": "^2.2.6",
"@types/react-router-dom": "^5.1.7",
"@typescript-eslint/eslint-plugin": "^4.26.1",
"@typescript-eslint/parser": "^4.26.1",
"axios": "^0.21",
"eslint": "^7.28.0",
"eslint-plugin-react": "^7.24.0",
"eslint-plugin-react-hooks": "^4.2.0",
"file-loader": "^6.2.0",
"laravel-mix": "^6.0.6",
"lodash": "^4.17.19",
"postcss": "^8.1.14",
"ts-loader": "^9.2.3",
"typescript": "^4.3.2"
},
"dependencies": {
"@hookform/resolvers": "^2.5.2",
"@material-ui/core": "^4.11.4",
"@material-ui/icons": "^4.11.2",
"js-cookie": "^2.2.1",
"react-hook-form": "^7.8.3",
"react-paginate": "^7.1.3",
"react-router-dom": "^5.2.0",
"yup": "^0.32.9"
}
}

我的tsconfig.json文件:

{
"extends": "@tsconfig/create-react-app/tsconfig.json",
"compilerOptions": {
//        "module": "CommonJS",
"target": "ES2020",
"sourceMap": true,
"jsx": "react",
"noEmit": false
},
"exclude": ["node_modules"],
"include": ["resources", "index.d.ts"]
}

my.eslintrc.json文件:

{
"env": {
"browser": true,
"es2020": true
},
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:@typescript-eslint/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 2020,
"sourceType": "module",
"project": "./tsconfig.json"
//        "tsconfigRootDir": "./resources"
},
"plugins": [
"react",
"@typescript-eslint",
"react-hooks"
],
"rules": {
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn"
}
}

问题是JavaScript正则表达式不支持条件构造,请参见正则表达式中的(?(?<=()...|...)。这意味着只有在第一个备选方案之前有一个(字符时,才会匹配它,否则,将尝试第二个备选方案。

我建议通过将(模式移动到后续组的第一个备选方案来完全消除条件(同时从模式中删除?以使其成为强制性的(:

/^+?d*s?(?:(d+)s?d+([-s.]?)(?:1?d)*|([.s-]?)(?:2?d)*)$/g
//            ^^

请参阅regex演示详细信息

  • ^-字符串的开头
  • +?-可选+
  • d*-零位或多位
  • s?-可选空白
  • (?:-非捕获组的启动:
    • (d+)-(,一个或多个数字,)
    • s?-可选空白
    • d+-一个或多个数字
    • ([-s.]?)-组1:可选-、空白或.
    • (?:1?d)*-后面跟任意一位数字的可选第1组值出现零次或多次
    • |-或
    • ([.s-]?)-组2:可选-、空白或.
    • (?:2?d)*-后面跟任意一位数字的可选第2组值出现零次或多次
  • )-组结束
  • $—字符串结束

最新更新