简体   繁体   English

仅当分隔符被引号括起时,才在Java中拆分字符串

[英]Splitting a string in Java only when a delimiter is surrounded by quote marks

Let's say I have the following string: 假设我有以下字符串:

"John Doe","IT,SI","foo, bar"

And I would like to split it into: 我想把它分成:

["John Doe", "IT,SI", "foo, bar"]

I was thinking to implement something like this: 我正在考虑实现这样的事情:

String line = "\"John Doe\",\"IT,SI\",\"foo, bar\"";
String[] lineItems = line.split("\",\"");

for (String lineItem : lineItems) {
    lineItem.removeAll("\"");
}

It does the thing, however this doesn't seem to be a state of art. 它做了这件事,但这似乎不是一种艺术状态。 Is there a better solution? 有更好的解决方案吗?

正则表达式适用于此案例。

String[] lineItems = line.split("(?<=\"),(?=\")");

以下内容应解决问题

line.split("(?<=\"),(?=\")") 

You wants the words between double quotes so instead of splitting the string you can use following regex to extract them : 你想要双引号之间的单词,所以不是拆分字符串,你可以使用后面的正则表达式来提取它们:

/"([^"]+)"/g

See demo https://regex101.com/r/hC3cW2/1 请参阅演示https://regex101.com/r/hC3cW2/1

(\b[^"]+)

Or you may name it also: 或者您也可以将其命名为:

(?P<names>\b[^"]+)
OR
(?<names>\b[^"]+)

Not sure java supports P<> or <> 不确定java是否支持P <>或<>

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

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