【问题标题】:Parse url structure by regular expression通过正则表达式解析url结构
【发布时间】:2020-10-12 01:54:02
【问题描述】:

我有一个 URL 模式:

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

产品/类别/page.html

product/page.html

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

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

我想通过一个regEx模式检测url及其参数

我在javascript中使用match函数

编辑:

我的路线模式:

product/cat?/page.html?

我想用这种模式制作regEx

? 在这个模式中意味着这个部分是可选的

例如:

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

结果:

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

当路由:product/computer/ram.html

正则表达式检测:

cat = computer

page = ram.html

【问题讨论】:

  • "product/cat/page.html".split(/[./]/)
  • 这些奇怪的字符“ۿ”是什么?正则表达式的目标是什么?检查它是否是特定路线?
  • @Kaddath \u0600-\u06FF,是的,通过模式列表检查 url 以了解到目的地的路线
  • @Andreas 正则表达式更快
  • “正则表达式更快” - 这只是一个意见

标签: javascript regex url


【解决方案1】:

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

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

【讨论】:

  • 谢谢lê-phi,但是如果 :cat 是可选的,发生了什么?
【解决方案2】:

这个正则表达式能解决你的问题吗?

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

在我的Regex101上尝试一些案例

【讨论】:

  • 我的问题已编辑,我想为自己制作正则表达式
猜你喜欢
  • 1970-01-01
  • 2010-09-19
  • 2011-03-20
  • 1970-01-01
  • 2011-02-24
  • 2016-06-15
  • 2012-08-23
  • 2012-06-15
相关资源
最近更新 更多