繁体   English   中英

Java正则表达式在空格上分割,不能在单引号或双引号之前或之后

[英]Java regex split on whitespace not preceded or followed by single or double quotes

我无法使它工作。

我有一个想在空格处分割的字符串。 但是,我不想在字符串内部拆分。 也就是说,双引号或单引号内的文本。

分割以下字符串:

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

..应产生以下令牌:

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

我可以为此使用哪种正则表达式?

正则表达式([^ "]*)|("[^"]*")应该与所有标记匹配。 利用我对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();
}

你有尝试过吗?

((['"]).*?\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)
)

另一方面,如果要创建解析器,请执行解析器并且不要使用正则表达式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM