2015-07-21 40 views
1

我已經在JavaScript中編寫了(?!,)(.*?)(?=,)正則表達式。訪問第一個第N個正則表達式組

這個正則表達式返回20個匹配組,但我想得到前5個組。

我該怎麼做?

+0

使用一些代碼。你講什麼語言? –

+0

這取決於你使用的語言,大多是'$ 1','$ 2',...被使用 – Tushar

+0

你想要的聲音['.slice()'](https://developer.mozilla.org/en -US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) –

回答

0

只需使用match/split然後slice陣列來獲得所需的物品:

var re = /[^,]+/g; 
 
var str = 'word1, word2, word3, word4, word5, word6, word7, word8, word9, word10, word11, word12, '; 
 

 
alert(str.match(re).slice(0, 5)); 
 

 
var splts = str.split(',').slice(0,5); 
 
alert(splts);

既然你只是尋找逗號之間的字符串,我建議使用[^,]+正則表達式。

相關問題