2014-11-24 36 views
4

這裏是我的正則表達式的簡化版本:如何獲得JavaScript正則表達式子匹配的位置?

re = /a(.*)b(.*)c(.*)d/; 
match = re.exec("axbxcxd"); 

正如預期的那樣,這將導致match[1]match[2]match[3]"x",但我需要得到中間匹配號碼2的位置在Python,我只能使用match.position(2)。在JavaScript中是否有任何等價的方法來獲得子匹配的位置?我不能只搜索匹配的字符串,因爲其他一些子匹配可能相同。

+1

只要用'match [2]'? – raser 2014-11-24 17:14:16

+1

@raser給你第二個匹配組的*文本*,而不是位置 – Jamiec 2014-11-24 17:16:48

+0

在匹配對象內搜索函數?匹配[2]。位置? – sln 2014-11-24 17:18:29

回答

-2

match對象有一些所謂的index,我認爲這是你在找什麼:

["axbxcxd", "x", "x", "x", index: 0, input: "axbxcxd"]


編輯

確定。我想我第一次沒有正確地回答這個問題。這裏是更新的答案:

re = /a(.*)b(.*)c(.*)d/; 
str = "axbxcxd"; 
match = re.exec(str); 
searchStr = match[1]; //can be either match[2],match[3] 
searchStrLen = match[1].length; //can be either match[2],match[3] 
var index, indices = [] 
var startIndex = 0; 
while ((index = str.indexOf(searchStr, startIndex)) > -1) { 
     indices.push(index); 
     startIndex = index + searchStrLen; 
} 
console.log(indices[1]); // index of match[2] 
console.log(indices[0]); // index of match[1] 
console.log(indices[2]); // index of match[3] .. and so on, because some people don't get it with a single example 

這可能是一個黑客,但應該工作。 工作小提琴:http://jsfiddle.net/8dkLq8m0/

+0

@Jamiec啊。說得通。但考慮到OP的問題中的例子,上面的代碼應該可以工作。 – 2014-11-24 17:32:53

+0

已刪除評論。大。 – 2014-11-24 17:34:08

+0

對不起,我刪除了我原來的評論,因爲我不想成爲smartass而沒有備份我的argumnet。除非是非常有限的(和人爲的)例子,否則你的編輯不起作用。看到這個:http://jsfiddle.net/oopf80wp/相同的模式,有效的輸入,但你的代碼不工作。 – Jamiec 2014-11-24 17:39:36

0

JavaScript沒有集成的API(還)來返回子匹配的位置。

關於添加這樣的API有一些discussion on the ECMAScript mailing list,儘管目前還沒有結果。

已經有一些工具,如regexplainedHiFi Regex Tester。雖然他們未能確定匹配字符串"aaa"/aa(a)/等子匹配的位置。

這些工具的作用是使用string.indexOf()搜索regexp.exec()返回的主要匹配內的子匹配。下面是一些示例代碼:

var string = "xxxabcxxx"; 
var regexp = /a(b(c))/g; 

var matches = regexp.exec(string); 
if (matches) { 
    matches[0] = { 
    text: matches[0], 
    pos: regexp.lastIndex - matches[0].length 
    }; 

    for(var i = 1; i < matches.length; i++) { 
    matches[i] = { 
     text: matches[i], 
     pos: string.indexOf(matches[i], matches[0].pos) 
    }; 
    } 
} 

console.log(matches); 

此輸出包含子匹配的位置匹配對象的數組:

[ 
    { 
     text: "abc", 
     pos: 3 
    }, 
    { 
     text: "bc", 
     pos: 3 
    }, 
    { 
     text: "c", 
     pos: 5 
    } 
    ] 

再次雖然注意到上面的代碼,像提到的工具,不不適用於所有情況。

相關問題