2014-02-18 60 views
1

在下面的代码中我没有得到正确的结果。我怎样才能在JavaScript中做模式匹配?javascript中的模式匹配

function getPathValue(url, input) { 
    console.log("this is path key :"+input); 
    url = url.replace(/%7C/g, '|'); 
    var inputarr = input.split("|"); 
    if (inputarr.length > 1) 
     input = '\\b' + inputarr[0] + '\n|' + inputarr[1] + '\\b'; 
    else 
     input = '\\b' + input + '\\b'; 

    var field = url.search(input); 
    var slash1 = url.indexOf("/", field); 
    var slash2 = url.indexOf("/", slash1 + 1); 
    if (slash2 == -1) 
     slash2 = url.indexOf("?"); 
    if (slash2 == -1) 
     slash2 = url.length; 
    console.log("this is path param value :"+url.substring(slash1 + 1, slash2)); 
    return url.substring(slash1 + 1, slash2); 
} 

getPathValue("http://localhost/responsePath/mountainwithpassid|accesscode/100/mountainwithpassid|passid/1","mountainwithpassid|passid") 

即时得到下面的输出

如果我通过mountainwithpassid | accesscode输入即时得到输出如果我通过

关键 100一样:mountainwithpassid | passid
值:100 //预期输出1

+1

那么,什么是正确的输出,你想要什么从URL? – turnt

+0

@Cygwinnian我的输入是mountainwithpassid | passid,它应该根据url返回1作为输出。 – user3180402

回答

1

如果你的意图是简单地检索在下面的输入路径的值(包含在“/”),那么你可以用更简单的正则表达式来实现。首先,您需要一种方法来转义输入字符串,因为它包含管道字符'|'它在正则表达式中被翻译为OR。

你可以使用这个(从https://stackoverflow.com/a/3561711拍摄):

RegExp.escape= function(s) { 
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); 
}; 

然后你getPathValue功能可以看起来像:

function getPathValue(url, input) { 
    var pathValue = null; 
    var escapedInput = RegExp.escape(input); 

    // The RegExp below extracts the value that follows the input and 
    // is contained within '/' characters (the last '/' is optional) 
    var pathValueRegExp = new RegExp(".*" + escapedInput + "/([^/]+)/?.*", 'g'); 

    if (pathValueRegExp.test(url)) { 
    pathValue = url.replace(pathValueRegExp, '$1'); 
    } 
    return pathValue; 
} 

您还需要考虑如何处理错误 - 在如果找不到匹配,则返回空值的示例。

0

我在试着理解这个问题。鉴于一个网址:

"http://localhost/responsePath/mountainwithpassid|accesscode/100/mountainwithpassid|passid/1" 

和的说法:

"mountainwithpassid|passid" 

你期望的返回值:

"1" 

"mountainwithpassid|accesscode" 

的说法应该返回:

"100" 

这是正确的吗?如果是这样(我不能肯定它是)那么下面可能适合:

function getPathValue(url, s) { 
    var x = url.indexOf(s); 
    if (x != -1) { 
     return url.substr(x).split('/')[1]; 
    } 
} 

var url = "http://localhost/responsePath/mountainwithpassid|accesscode/100/mountainwithpassid|passid/1"; 
var x = "mountainwithpassid|passid"; 
var y = "mountainwithpassid|accesscode"; 

console.log(getPathValue(url, x)); // 1 
console.log(getPathValue(url, y)); // 100