2013-02-17 58 views
1

我想提取()括号内的文本。该字符串看起来是这样的:它是内如何提取圆括号之间的文本?

Some text: 5 (some numbers) + some more numbers 
asdfkjhsd: 7 (6578) + 57842 
djksbcuejk: 4 (421) + 354 

我的JavaScript看起来像这样:

var fspno = document.getElementsByTagName("td")[142].innerText; 
var allfsp = fspno.match(); 

我想这个脚本来收集括号内的所有数字在数组中。我用

fspno.match(/\((.*?)\)/g); 

但它与括号一起返回。我只想要括号内的文字。 任何帮助,将不胜感激。谢谢。

回答

1

有在javascript没有办法提取全部一次与各组的比赛,所以你要么需要循环使用exec

re = /\((.+?)\)/g 
found = [] 
while(r = re.exec(fspno)) 
    found.push(r[1]) 

或滥用String.replace到收集匹配:

re = /\((.+?)\)/g 
found = [] 
fspno.replace(re, function($0, $1) { found.push($1)}) 

然而,在您的特定情况下,可以重写表达式,以便它不包含组并且可以使用String.match

re = /[^()]+(?=\))/g 
found = fspno.match(re) 
+0

谢谢。这工作完美。 – 2013-02-17 09:17:17

0
/\((.*?)\)/.exec('7 (6578) + 57842')[1] 
0

最简单的方法是关闭g选项,并获得了比赛的[1]指标,如:

fspno.match(/\((.*?)\)/)[1]; 

但如果没有找到,将返回一个错误,所以如果你不“知道,如果你有一个括号中的部分或没有,或者你可以使用这个成语:

(fspno.match(/\((.*?)\)/) || [,""])[1]; 

将返回"",如果它不能找到一个匹配。

如果你知道你需要的g选项(即有可能是在括号中不止一件事,你希望他们所有的),你可以使用:

var match, matches=[]; while (match = /\((.*?)\)/g.exec(s)) matches.push(match[1]); 
// matches is now an array of all your matches (without parentheses) 
0

您可能不需要g选项。 fiddle here

var fspno = "7 (6578) + 57842"; 
var found = fspno.match(/\((.*?)\)/); 

if (found) { 
    var found1 = found[1]; 
    alert(found1); 
} 
相关问题