通过正则表达式解析url结构 [英] Parse url structure by regular expression

查看:25
本文介绍了通过正则表达式解析url结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 URL 模式:

I have one URL pattern :

product/[cat]/[page].[ext]

product/category/page.html

product/page.html

但是我的正则表达式不能正常工作:

But my Regular Expression does not work properly :

^product\/([\w\d\.\-_\s\'\"\(\)\[\]\؀-\ۿ](?!.*\.html))*\/([\w\d\.\-_\s\'\"\(\)\[\]\؀-\ۿ]+\.html+)*\/?$

我想通过一个 regEx 模式检测 url 和它的参数

I want by one regEx pattern detect url and it parameters

我在javascript中使用match函数

I use match function in javascript

我的路线模式:

product/cat?/page.html?

我想通过这种模式制作 regEx

I want make regEx by this pattern

? 在这个模式中表示这个部分是可选的

? in this pattern means this section is optional

例如:

makeRegEx('product/cat?/page.html?')

结果:

^product\/([\w\d\.\-_\s\'\"\(\)\[\]\؀-\ۿ](?!.*\.html))*\/([\w\d\.\-_\s\'\"\(\)\[\]\؀-\ۿ]+\.html+)*\/?$

路由时: product/computer/ram.html

正则表达式检测:

cat = 电脑

page = ram.html

推荐答案

这是生成回归的函数,解决了您的问题.

this is function to generate regression solved your problem.

function makeRegEx(route, url) {
    let pattern = new RegExp('(:([a-z]+))(\\??)', 'g');
    let match = route.match(pattern);
    let route_regex = route.replace(/\//g, '\\/').replace(/\./g, '(\\.*)');
    for(let params of match) {
        let required = params.includes('?') ? '*' : '+';
        route_regex = route_regex.replace(params, '([a-z_\\-]'+required+')')
    }
    let params_match = url.match(route_regex);
    let map_params;
    if (params_match) {
        map_params = match.map((item, key) => { return {param: item, value: params_match[key + 1]} });
    } else {
        map_params = 'missing required params';
    }

    return {
        url, route, route_regex, map_params
    }

}
// test cases:
console.log(makeRegEx('product/:cat/:page.html', 'product//.html'));
console.log(makeRegEx('product/:cat/:page.html', 'product/computer/.html'));
console.log(makeRegEx('product/:cat/:page.html', 'product/computer/cpu.html'));

console.log(makeRegEx('product/:cat/:page?.html', 'product//cpu.html'));
console.log(makeRegEx('product/:cat/:page?.html', 'product/computer/.html'));
console.log(makeRegEx('product/:cat/:page?.html', 'product/computer/cpu.html'));

console.log(makeRegEx('product/:cat/:page.:type', 'product/computer/.html'));
console.log(makeRegEx('product/:cat/:page.:type', 'product//.html'));
console.log(makeRegEx('product/:cat/:page.:type', 'product/computer/cpu.html'));

console.log(makeRegEx('product/:cat/:page.:type?', 'product/computer/cpu'));
console.log(makeRegEx('product/:cat/:page.:type?', 'product/computer/cpu.html'));

这篇关于通过正则表达式解析url结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆