2014-02-07 38 views
2

我想使用空格拆分字符串,但不考慮雙引號或單引號。java - 正則表達式使用空格拆分字符串,但不考慮雙引號或單引號

我試過使用Regex for splitting a string using space when not surrounded by single or double quotes,但在某些情況下失敗了。

Input : It is a "beautiful day"'but i' cannot "see it" 

和輸出應該是

It 
is 
a 
"beautiful day"'but i' 
cannot 
"see it" 

在上面的鏈接的正則表達式導致

It 
is 
a 
"beautiful day" 
'but i' 
cannot 
"see it" 

我想在一個行"beautiful day"'but i'

有人能幫我寫出正確的正則表達式嗎?

回答

5

此正則表達式通過測試:

" (?=(([^'\"]*['\"]){2})*[^'\"]*$)" 

它是在一個空間拆分,但只有當空間不是引號內,它測試用前瞻斷言有偶數個空間後面的引號。

有一些邊緣情況下這不起作用,但如果你的輸入是「良好的」(即引號是平衡的),這將適用於你。如果報價不平衡,它仍然是可行的 - 您需要使用兩個前瞻 - 每個報價類型一個。


下面是一些測試代碼:

String s = "It is a \"beautiful day\"'but i' cannot \"see it\""; 
String[] parts = s.split(" (?=(([^'\"]*['\"]){2})*[^'\"]*$)"); 
for (String part : parts) 
    System.out.println(part); 

輸出:

It 
is 
a 
"beautiful day"'but i' 
cannot 
"see it" 
+0

當我修改,以**這是一個\ 「美麗day'but我」 \」 不能串\ 「看到它」**它失敗了。請你解釋它是如何工作的? –

+1

請告訴我這個新的字符串「成功」的樣子。 – Bohemian

+0

所需的輸出就像**「美麗的一天」,但我**。但我得到**「」美麗的一天「,但我**和**」我「不能連續行**」 –

相關問題