2014-11-24 37 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 
    } 
    ] 

再次虽然注意到上面的代码,像提到的工具,不不适用于所有情况。

相关问题