簡體   English   中英

通過正則表達式解析url結構

[英]Parse url structure by regular expression

我有一個URL模式:

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

產品/類別/頁面.html

產品/頁.html

但我的正則表達式不能正常工作:

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

我想通過一種正則表達式模式檢測regEx及其參數

我在 javascript 中使用match function

編輯:

我的路線模式:

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\/([a-zA-Z]+)\/*([a-zA-Z]+)\.([a-zA-Z]+)

在我的Regex101上嘗試一些案例

這是 function 生成回歸解決了你的問題。

 function makeRegEx(route, url) { let pattern = new RegExp('(:([az]+))(\\??)', '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'));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM