javascript正则表达式返回嵌入在文档字符串中的值数组

时间:2014-02-05 06:44:54

标签: javascript regex

所以我真的没有得到正则表达式的细微差别(甚至是基础知识),所以我只想问是否有人可以生成一个通过以下字符串的Javascript Regex,是否为item / regex并返回一个数组[4,378,382]:

var tmp_str="here is <a href='/arc/item/4'>item - more item stuff</a> and there are other things <a href='/arc/item/378'>another item - more item stuff</a> and finally <a href='/arc/item/382'>last item - more item stuffvar </a>"

我很乐意提出任何正确答案。

我认为(但显然不起作用):

var myRe = /item\/(b+)\'/g;
var myArray = myRe.exec(tmp_str);
// myArray should have the values

帮我Stack Overflow偷看,你是我唯一的希望

1 个答案:

答案 0 :(得分:3)

使用\d匹配数字:

tmp_str.match(/item\/\d+/g)
// => ["item/4", "item/378", "item/382"]
tmp_str.match(/item\/\d+/g).map(function(m) { return m.substr(5); })
// => ["4", "378", "382"]
tmp_str.match(/item\/\d+/g).map(function(m) { return m.match(/\d+/)[0] })
// => ["4", "378", "382"]