2013-05-20 10 views
1

我必須拆分輸入逗號分隔的字符串並將結果存儲在數組中。如何通過轉義雙引號文本來拆分字符串

偉大

arr=inputString.split(",") 

這個例子以下工作

John, Doe  =>arr[0]="John"  arr[1]="Doe" 

但未能獲得預期的輸出

"John, Doe", Dan =>arr[0]="John, Doe" arr[1]="Dan" 
John, "Doe, Dan" =>arr[0]="John"  arr[1]="Doe, Dan" 

按照下面的正則表達式也沒有幫助

 var regExpPatternForDoubleQuotes="\"([^\"]*)\""; 
     arr=inputString.match(regExpPatternForDoubleQuotes); 
     console.log("txt=>"+arr) 

該字符串可能包含兩個以上的雙引號。

我在JavaScript中嘗試以上。

+0

感謝您的鏈接。不知道它已經回答了。但鏈接的答案非常冗長而且很好。這裏的答案很簡短。我比較喜歡後者。 – Watt

回答

2

這工作:

var re = /[ ,]*"([^"]+)"|([^,]+)/g; 
var match; 
var str = 'John, "Doe, Dan"'; 
while (match = re.exec(str)) { 
    console.log(match[1] || match[2]); 
} 

它是如何工作的:

/ 
    [ ,]*  # The regex first skips whitespaces and commas 
    "([^"]+)" # Then tries to match a double-quoted string 
    |([^,]+) # Then a non quoted string 
/g   # With the "g" flag, re.exec will start matching where it has 
       # stopped last time 

試一下:http://jsfiddle.net/Q5wvY/1/

+0

+1。這是我需要的。 – Watt

0

嘗試使用此模式與 EXEC方法:

/(?:"[^"]*"|[^,]+)+/g 
相關問題