[英]String enclosed with double quotes splitting issue
I have a String in the below format. 我有以下格式的字符串。
"test","2, High Street, 50100 Eastleigh",",UK"
when i split the above string using below code 当我使用下面的代码分割上面的字符串时
String[] lineArr = line.split("\",", -1)
Actual output is: 实际输出为:
"test
"2, High Street, 50100 Eastleigh
UK"
Expected Output is: 预期输出为:
test
2, High Street, 50100 Eastleigh
,UK
How do i handle this? 我该如何处理?
You can ignore the first and last "
, and split on ","
, as follows: 您可以忽略第一个和最后一个"
,并分割为","
,如下所示:
String[] lineArr = line.substring(1,line.length()-1).split("\",\"");
I am sure there are more efficient and elegant solutions, but this should be an easy adaptation of your code with an one-liner. 我敢肯定会有更有效,更优雅的解决方案,但这应该是单线轻松修改您的代码。
split(String match, int limit)
If limit is non-positive then the pattern will be applied as many times as possible and the array can have any length. 如果limit为非正数,则该模式将被尽可能多地应用,并且数组可以具有任何长度。 If limit is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded. 如果limit为零,则该模式将被尽可能多地应用,该数组可以具有任何长度,并且尾随的空字符串将被丢弃。
"test","2, High Street, 50100 Eastleigh","
Here when you apply lineArr.split("\\",",-1)
, limit is negative, it will return trailing empty strings as well, 在这里,当您应用lineArr.split("\\",",-1)
,limit为负,它也会返回尾随的空字符串,
test
, "2, High Street, 50100 Eastleigh
and empty string ""
, Hence giving you 3
as length. test
, "2, High Street, 50100 Eastleigh
和empty string ""
,因此给您3
作为长度。
However if you use lineArr.split("\\",",0)
or lineArr.split("\\",")
no trailing empty strings are returned. 但是,如果您使用lineArr.split("\\",",0)
或lineArr.split("\\",")
不会返回结尾的空字符串。 So you will be getting 2
as length. 因此,您将获得2
作为长度。
To eliminate in between empty strings i would recommend you to use lineArr.split("\\",");
which is split(String match)
version of above split method
为了消除空字符串之间的lineArr.split("\\",");
我建议您使用lineArr.split("\\",");
它是上述split method
split(String match)
版本
According to your output you should call lineArr.split("\\",\\"");
根据您的输出,您应该调用lineArr.split("\\",\\"");
, this will give your resultant output. ,这将为您提供最终的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.