2012-12-14 31 views
1

我有这种类型的JSON数组:支架正则表达式的Javascript

[ 
    { text: '[Chapter1](chapter1.html)'}, 
    { text: '[Chapter2](chapter2.html)'}, 
    { text: '[Chapter3](chapter3.html)'}, 
    { text: '[Chapter4](chapter4.html)'} 
] 

在试图环槽的阵列和取括号中的文本(第1章,第2章等)I found a RegExp here at StackOverflow

var aResponse = JSON.parse(body).desc; // the array described above 
var result = []; 
var sectionRegex = /\[(.*?)\]/; 
for(var x in aResponse) { 
    result.push(sectionRegex.exec(aResponse[x].text)); 
    //console.log(aResponse[x].text) correctly returns the text value 
} 
console.log(result); 

应打印:

["Chapter1","Chapter2","Chapter3","Chapter4"] 

但是我得到了多个阵列怪异的长期结果:

[ '[Chapter1]', 
    'Chapter1', 
    index: 0, 
    input: '[Chapter1](chapter1.html)' ] 
[ '[Chapter2]', 
    'Chapter2', 
    index: 0, 
    input: '[Chapter2](chapter2.html)' ] 
[ '[Chapter3]', 
    'Chapter3', 
    index: 0, 
    input: '[Chapter3](chapter3.html)' ] 
[ '[Chapter4]', 
    'Chapter4', 
    index: 0, 
    input: '[Chapter4](chapter4.html)' ] 

我缺少什么?我吮吸正则表达式。

+0

不知道你用JSON.parse那里所做的事情,但这里有一个[** ** FIDDLE(HTTP://的jsfiddle。净/ xGXD8/2 /),也许这使得它更清晰? – adeneo

+0

我使用GET请求从外部服务器获取JSON。我不知道什么是错的。我检查了一切。它仍然返回甚至不在json数组中的字段。 – jviotti

+0

@adeneo我附上了我得到的结果 – jviotti

回答

1

The exec method of regular expressions不仅返回匹配的文本,还返回许多其他信息,包括输入,匹配索引,匹配文本和所有捕获组的文本。你可能想比赛第1组:

result.push(sectionRegex.exec(aResponse[x].text)[1]); 

除此之外,你不应该使用for(...in...)循环遍历数组,因为这将打破,如果任何方法添加到Arrayprototype。 (例如,forEach垫片)

0

没有你想象的那么奇怪,每个regex.exec结果实际上是一个看起来像其中一个块的对象,它包含整个文本匹配,子组匹配(你只有一个子组,并且它是你真正想要的结果),匹配成功的输入内的索引和给出的输入。

所有这些都是成功比赛的有效结果。

简短的回答是,你想只推动第二个数组元素到结果中。
Like regex.exec(text)[1]

+1

更多信息:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/exec –

0

您使用的正则表达式将返回一个数组。 第一个元素将是要测试的字符串。下一个元素将是括号 之间的matche试试这个:

result.push(sectionRegex.exec(aResponse[x].text)[1]);