问题
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