Javascript正则分组命名

Javascript的正则分组不支持命名,只好自己搞了一个。先把命名存入数组,然后匹配。

唉~~~有更好的解决方案么?

image

代码:

var route = '/{controller}/{action}/{id}',
    url = '/home/index/2';

groupRE(route, url); // ==> {controller:'home', action:'index', id:'2'}

/*
* @re: string, e.g.: '/{controller}/{action}/{id}'
* @s: string to match, e.g.: 'home/index/2'
* @return: dict, e.g.: {controller:'home', action:'index', id:'2'}
*/
function groupRE(re, s){
    var names = [], result = {}, cursor = 0;
    re = re.replace(/\{([^}]+)\}/g, function(m, g1){
        names.push(g1);
        return '(.+)';
    });
    re = new RegExp(re);
    var tmp = re.exec(s);
	if(tmp){
		for(var i=1; i<tmp.length; i++){
			if(names[i-1]){
				result[ names[i-1] ] = tmp[i];
			}
		}
	}
    return result;
}

posted on 2011-03-16 16:02  Q.Lee.lulu  阅读(2598)  评论(1编辑  收藏  举报