2012-04-03 46 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

相关问题