2012-04-03 48 views
0

我不能得到這個工作..Java的正則表達式不分裂之前或之後單或雙引號

我有,我想拆就空格的字符串。不過,我不想在Strings裏面分割。也就是說,內部是雙引號或單引號的文本。

分割以下字符串:

private String words = " Hello, today is nice " ; 

..should產生以下令牌:

private 
String 
words 
= 
" Hello, today is nice " 
; 

我可以使用什麼樣的正則表達式的這個?

+0

不應該這樣做嗎? 「[^ \\ s \」'] + | \「[^ \」] * \「|'[^'] *'」 – jpaw 2012-04-03 14:02:15

+0

Duplicate of [this](http://stackoverflow.com/questions/366202/regex-for-splitting-a-string-using-space-when-not-surround-by-single-or-double) – 2012-04-03 14:09:46

+0

正在看着它,但認爲它是不同的。現在我意識到這是同一個問題。抱歉! – jpaw 2012-04-03 15:23:39

回答

0

正則表達式([^ "]*)|("[^"]*")應該匹配所有的標記。借鑑我有限的Java和http://www.regular-expressions.info/java.html的知識,你應該能夠做這樣的事情:

// Please excuse any syntax errors, I'm used to C# 
Pattern pattern = Pattern.compile("([^ \"]*)|(\"[^\"]*\")"); 
Matcher matcher = pattern.matcher(theString); 
while (matcher.find()) 
{ 
    // do something with matcher.group(); 
} 
+0

感謝隊友。這適用於我的應用程序,它運行良好。 – jpaw 2012-04-04 08:14:30

0

你試過嗎?

((['"]).*?\2|\S+) 

這裏是做什麼的:

(  <= Group everything 
    (['"]) <= Find a simple or double quote 
    .*?  <= Capture everything after the quote (ungreedy) 
    \2  <= Find the simple or double quote (same as we had before) 
    |  <= Or 
    \S+  <= Non space characters (one at least) 
) 

在另一方面,如果你想創建一個解析器,做一個解析器和不使用正則表達式。

+0

試過這個..但它並沒有提取任何令牌,因爲某種原因..也許不適合拆分方法? String [] tokens = myString.get(x).split(「((['\」])。*?\\ 2 | \\ S +)「); – jpaw 2012-04-04 08:13:38

相關問題