【问题标题】:Typescript regex parse just value not whole match打字稿正则表达式只解析值而不是整个匹配
【发布时间】:2023-01-07 16:11:44
【问题描述】:

例如“/mentor/33 是 url”

我用正则表达式来做到这一点: buildRegex('/mentor/:id');

'/mentor/:id' 变成 '/mentor/[^/]'

const PATH_PARAM = {
    PREFIX: ':',
    REGEX_IDENTIFIER: '/:[^/]+',
    REGEX_REPLACER: '/[^/]+',
};

private buildRegex(path: string) {
        return this.ensureLeadingSlash(path).replace(
            new RegExp(PATH_PARAM.REGEX_IDENTIFIER, 'g'),
            PATH_PARAM.REGEX_REPLACER
        );
    }

我怎样才能从 [^/] 取回 33,所以值?

如果我用这个

private matchRegex(routeLink: string, routeRegex: string) {
        const match = routeLink.match(new RegExp(routeRegex, "g"));
        return match?.[0];
    }

然后我返回 /mentor/33 而不是 33。我正在寻找通用方法。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    将替换的模式包围成一个组,然后在匹配后引用该组而不是 [0]。该组是应该是PATH_PARAM 的一部分还是在调用buildRegex 时动态构建将取决于您的情况以及什么是动态的。

    因为您只执行一次匹配,所以不要使用全局标志。

    const PATH_PARAM = {
        PREFIX: ':',
        REGEX_IDENTIFIER: '/:[^/]+',
        REGEX_REPLACER: '/[^/]+',
    };
    const buildRegex = (path) => {
        return path.replace(
            new RegExp(PATH_PARAM.REGEX_IDENTIFIER),
            `(?<pathinfo>${PATH_PARAM.REGEX_REPLACER})`
        );
    };
    const pattern = buildRegex('/mentor/:id');
    const matchRegex = (routeLink, routeRegex) => {
        const match = routeLink.match(routeRegex);
        return match?.groups.pathinfo;
    }
    console.log(matchRegex('/mentor/33', pattern));

    如果前导/有问题,请注意/是包含在您的REGEX_IDENTIFIER 和REGEX_REPLACER 中。之后将第一个字符切出,或者更改 REGEX_IDENTIFIER 和 REGEX_REPLACER 以删除斜杠,或者将组放入 PATH_PARAM 对象本身而不是动态构造它。

    const PATH_PARAM = {
        PREFIX: ':',
        REGEX_IDENTIFIER: '/:[^/]+',
        REGEX_REPLACER: '/(?<pathinfo>[^/]+)',
    };
    const buildRegex = (path) => {
        return path.replace(
            new RegExp(PATH_PARAM.REGEX_IDENTIFIER),
            PATH_PARAM.REGEX_REPLACER
        );
    };
    const pattern = buildRegex('/mentor/:id');
    const matchRegex = (routeLink, routeRegex) => {
        const match = routeLink.match(routeRegex);
        return match?.groups.pathinfo;
    }
    console.log(matchRegex('/mentor/33', pattern));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 2015-05-06
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      • 1970-01-01
      • 2023-01-25
      相关资源
      最近更新 更多