我使用Java编写代码并返回一个类似于此字符串的方法 -
0, 2, 23131312,"This, is a message", 1212312
我希望字符串像 -
一样吐["0", "2", "23131312", "This, is a message", "1212312"]
当我在逗号上使用分割字符串方法时,它会分割"这是一条消息"同样,我也不想要。如果可能的话,我希望它忽略那个特殊的逗号并删除双引号。
我查了一些答案,CSV似乎就是这样做的。但是,我不能理解它。
感谢任何帮助。
答案 0 :(得分:1)
我认为你可以从这里使用正则表达式,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)
:Splitting on comma outside quotes
您可以在此处测试模式:http://regexr.com/3cddl
Java代码示例:
public static void main(String[] args) {
String txt = "0, 2, 23131312,\"This, is a message\", 1212312";
System.out.println(Arrays.toString(txt.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)")));
}
答案 1 :(得分:0)
一种更简单的方法是将主字符串转换为json对象数组,该数组自动处理实际元素并为您提供对象数组。
答案 2 :(得分:0)
另一种方法是迭代字符串,保存索引,当你点击" ",执行String.substring并插入数组,并更新索引。当你点击双引号(")时,你会寻找另一个双引号,并将子字符串插入数组并更新索引。
答案 3 :(得分:0)
我将评论基于编程算法的解决方案,无需任何库的帮助。我不说这比使用库更好。
首先,这个问题比初看起来有更多的怪癖。我的意思是:
0,1,"string"notcomma,hi
"This, is a ""message"""
)。这些也应该正确解析。如果(看起来)非引用的值总是数字(或者,至少是无空格),我会寻找扫描字符串的解决方案:
class StringScanner
{
private final String s;
private int currentPosition;
public StringScanner (String s)
{
this.s = s;
this.currentPosition = 0;
skipWhitespace ();
}
private void skipWhitespace ()
{
while (currentPosition < s.length() && s.charAt (currentPosition) == ' ')
currentPosition++;
}
private String nextNumber ()
{
final int start = currentPosition;
while (currentPosition < s.length() && s.charAt (currentPosition) != ' ')
currentPosition++;
return s.substring (start, currentPosition);
}
private String nextString ()
{
if (s.charAt (currentPosition) != '\"')
throw new Error ("You should NEVER see this error, no matter what the input string is");
currentPosition++;
final int start = currentPosition;
// Modify the following loop to test for escaped quotes if necessary
while (currentPosition < s.length() && s.charAt (currentPosition) != '\"')
currentPosition++;
if (currentPosition >= s.length || s.charAt (currentPosition) != '\"')
throw new Error ("Parse error: Unterminated string");
final String r = s.substring (start, currentPosition);
currentPosition++;
return r;
}
public String nextField ()
{
String r;
if (currentPosition >= s.length ())
r = null;
else if (s.charAt (currentPosition) == '\"')
r = nextString ();
else
r = nextNumber ();
skipWhitespace ();
if (currentPosition < s.length () && s.charAt (currentPosition) != ',')
throw new Error ("Parse error: no comma at end of field");
currentPosition++;
skipWhitespace ();
if (currentPosition >= s.length ())
throw new Error ("Parse error: string ends with comma");
return r;
}
}
然后,用以下内容分割字符串:
String s = "0, 1, \"Message, ok?\", 55";
StringScanner ss = new StringScanner (s);
String field = ss.nextField ();
while (field != null)
{
System.out.println ("Field found: \"" + field + "\"");
field = ss.nextField ();
}