result = ' hello "my name" is "Tom"'.split(/\s+(?=(?:[^"]*"[^"]*")*[^"]*$)/)
將爲您工作。它會打印
=> ["", "hello", "\"my name\"", "is", "\"Tom\""]
只是忽略空字符串。
說明
"
\\s # Match a single character that is a 「whitespace character」 (spaces, tabs, and line breaks)
+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
(?= # Assert that the regex below can be matched, starting at this position (positive lookahead)
(?: # Match the regular expression below
[^\"] # Match any character that is NOT a 「\"」
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\" # Match the character 「\"」 literally
[^\"] # Match any character that is NOT a 「\"」
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\" # Match the character 「\"」 literally
)* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
[^\"] # Match any character that is NOT a 「\"」
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\$ # Assert position at the end of a line (at the end of the string or before a line break character)
)
"
您可以使用reject
這樣避免空字符串
result = ' hello "my name" is "Tom"'
.split(/\s+(?=(?:[^"]*"[^"]*")*[^"]*$)/).reject {|s| s.empty?}
打印
=> ["hello", "\"my name\"", "is", "\"Tom\""]
+1。好答案! – Swanand
偉大的正則表達式的解剖。很有幫助。 –
這不會刪除特殊字符。 – 2011-11-17 05:49:03