【问题标题】:Java regex split on whitespace not preceded or followed by single or double quotesJava 正则表达式在空格上拆分,前面或后面没有单引号或双引号
【发布时间】:2023-03-31 11:07:01
【问题描述】:

我不能让它工作..

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

例子

拆分以下字符串:

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

..应该产生以下标记:

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

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

【问题讨论】:

  • 不应该这样工作吗? "[^\\s\"']+|\"[^\"]*\"|'[^']*'"
  • 重复this
  • 正在查看它,但认为它有所不同。现在我意识到这是同一个问题。对不起!

标签: java regex split quotes


【解决方案1】:

你试过了吗?

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

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

【讨论】:

  • 试过这个..但由于某种原因它根本没有提取任何标记..可能不适合拆分方法? String[] tokens = myString.get(x).split("((['\"]).*?\\2|\\S+)");
【解决方案2】:

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

【讨论】:

  • 谢谢伙计。这适用于我的应用程序并且效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多