Parse url structure by regular expression

杀马特。学长 韩版系。学妹 提交于 2021-01-29 09:35:46

问题


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+)*\/?$

I want by one regEx pattern detect url and it parameters

I use match function in javascript

EDIT :

my route pattern :

product/cat?/page.html?

I want make regEx by this pattern

? in this pattern means this section is optional

For example :

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

result:

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

when route : product/computer/ram.html

regular expression detect :

cat = computer

page = ram.html


回答1:


Is this regular expression solving your problem ?

^product\/([a-zA-Z]+)\/*([a-zA-Z]+)\.([a-zA-Z]+)

Try some cases on my Regex101




回答2:


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'));


来源:https://stackoverflow.com/questions/62510438/parse-url-structure-by-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!