2014-03-30 17 views
1

如果我有多個匹配的正則表達式像匹配:如何「的地方保持」正則表達式中的數組使用javascript

var matches = string.match(/\s*(match1)?\s*(match2)?(match3)?\s*/i); 

,如果我的字符串,我測試的是這樣的:

var string = "match1 match3"; 

是有辦法輸出數組值:

matches[1] = "match1"; 
matches[2] = ""; 
matches[3] = "match3"; 

注意:我想什麼是正則表達式匹配整個事情,但「地方 - 在陣列中保持它沒有找到的匹配。

希望這是有道理的。謝謝您的幫助!

+1

已經有一個「placeho lder連續」。例如''match2「.match(/ \ s *(match1)?\ s *(match2)?(match3)?\ s */i);'returns'[」match2「,undefined,」match2「,undefined] '[0]'是完整的正則表達式匹配,'[1] [2] [3]'是個別組 –

回答

3

已經有一個「placehol DER」。不匹配的組彈出與未定義的值匹配的組編號的數組索引。例如

var someString = "match2"; 
var matches = someString.match(/\s*(match1)?\s*(match2)?(match3)?\s*/i); 

matches現在有

["match2", undefined, "match2", undefined]

0是完整的正則表達式匹配和元素1-3的各組

所以,你可以做例子......

// check if group1 
if (typeof matches[1] != 'undefined') 
0

當你想將字符串比較的正則表達式,只是做一個Array join.Something一樣,

matches[1] = "match1"; 
matches[2] = ""; 
matches[3] = "match3"; 
var mystring = mathches.join(""); 

的連接字符可以是任何東西。你也可以做,

var mystring = mathches.join(" "); 

編輯: 從問題的描述不知道,但我想你想的正則表達式輸出像

的array.Something
text = "First line\nSecond line"; 
var regex = /(\S+) line\n?/y; 

會給,

var match = regex.exec(text); 
print(match[1]); // prints "First" 
print(regex.lastIndex); // prints 11 

更多關於它here

+0

這不完全是我所要求的...我期待有正則表達式輸出一個數組看起來像那樣,而不是將比賽與原始比較。 –

+0

正則表達式比較的輸出只能是「true」/「false」 –

+0

['.match'](http://www.w3schools.com/jsref/jsref_match.asp)匹配不會像['.exec '](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) – abc123

相關問題