繁体   English   中英

正则表达式以匹配Node.js中的url模式

[英]Regex to match the url pattern in nodejs

我正在开发一个节点应用程序,我需要一个正则表达式来匹配url模式并从url中获取信息,并提出可能的解决方案。

This are the url patterns:
1) www.mysite.com/Paper/cat_CG10
2) www.mysite.com/White-Copy-Printer-Paper/cat_DP5027
3) www.mysite.com/pen/directory_pen?
4) www.mysite.com/Paper-Mate-Profile-Retractable-Ballpoint-Pens-Bold-Point-Black-Dozen/product_612884
5) www.mysite.com/22222/directory_22222?categoryId=12328

These is what is want from the above url:
1) name= "cat" value="CG10"
2) name= "cat" value="DP5027"
3) name= "directory" value ="pen"
4) name="product" value ="612884"
5) name="directory" value="22222" params = {categoryId : 12328}

I want a regex which can match the url pattern and get the values like name, value and params out of the urls.

此功能可以解决您提供的网址和所需匹配项的问题。 它还将解析出无限数量的查询参数。

小提琴: http : //jsfiddle.net/8a9nK/

function parseUrl(url)
{
    var split = /^.*\/(cat|directory|product)_([^?]*)\??(.*)$/gi.exec(url);
    var final_params = {};
    split[3].split('&').forEach(function(pair){
       var ps = pair.split('=');
       final_params[ps[0]] = ps[1];
    });
    return {
        name: split[1], 
        value: split[2], 
        params: final_params
    };
}

说明

^从字符串开头
.*匹配任意数量的任何内容(我们不在乎的url的开头)
\\/匹配一个反斜杠(我们关心的事情之前的最后一个)
(cat|directory|product)匹配并捕获单词cat OR directory OR product(这是我们的名称
_匹配下划线(将我们的名字分开的字符)
([^?]*)匹配并捕获除问号以外的任何其他内容(这是我们的价值
\\?? 匹配问号(如果存在),否则不必担心(潜在查询字符串的开头)
(.*)匹配并捕获任意数量的任何内容(这是我们稍后将拆分为参数的整个查询字符串)
$匹配字符串的结尾

下面的正则表达式在其匹配组1和2中将具有所需的值

/^\/[^\/]+\/([^_]+)_([^\/_?]+).*$/

对字符串/HP-ENVY-TouchSmart-m7-j010dx-173-Touc‌​h-Screen-Refurbished-Laptop/product_8000进行和平解释:

  • ^ :从头开始
  • \\/ :匹配一个/
  • [^\\/]+ :匹配所有内容,直到/HP-ENVY-TouchSmart-m7-j010dx-173-Touc‌​h-Screen-Refurbished-Laptop
  • \\/ :匹配一个/
  • ([^_]+)匹配并捕获_product )之前的值
  • _ :匹配_
  • ([^\\/_?]+)匹配并捕获_并以?停止后的值? _/8000
  • .*匹配到最后-如果有的话
  • $结束

例:

var re = /^[^\/]+\/[^\/]+\/([^_]+)_([^\/_?]+).*$/;
var matches = re.exec('www.mysite.com/22222/directory_22222?categoryId=12328');
console.log(matches.splice(1));

输出:

["directory", "22222"]

使用url模块可以为您提供帮助,而不是需要使用正则表达式来完成所有工作:)

var uri = require( 'url' ).parse( 'www.mysite.com/22222/directory_22222?categoryId=12328', true );

产生(与其他东西):

{ 
  query: { categoryId: '12328' },
  pathname: 'www.mysite.com/22222/directory_22222'
}

现在得到您的最后一部分:

uri.pathParams = {};
uri.pathname.split('/').pop().split('_').forEach( function( val, ix, all ){
    (ix&1) && ( uri.pathParams[ all[ix-1] ] = val );
} );

产生:

{ 
  query: { categoryId: '12328' },
  pathParams: { directory: '22222 },

  ... a bunch of other stuff you don't seem to care about
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM