简体   繁体   English

在Java中,如何分割这些行?

[英]In Java, how to split lines like these?

I know how to use Java's string split method, like this 我知道如何使用Java的字符串拆分方法,像这样

String s="a,b,c";
s.split(",");

But how to split the following lines : 但是如何分割以下几行:

 FirstName,LastName,Companies,Title,EmailAddress,PhoneNumbers,Tags,Note
 Tom,Smith,ABC Co.,Manager,toms@xyz.com,,,
 John,White,"Some-Company, Inc.","Network Manager, Architect",xyz@abc.com,,,

It's easy to handle the 1st 2 lines, but the 3rd line has some trouble, because it's including [,] inside ["], any suggestions ? 处理第一行和第二行很容易,但是第三行有一些麻烦,因为它在[“]内包含[,],有什么建议吗?

Edit : I've looked into the other 2 similar questions and answers, but they are different from my question, my question has [,] as delimiter, other 2 questions have a space character as delimiter, and space is also present in my question which complicates matter, so if I use that answer, it won't work, please don't mark it as a duplicate. 编辑:我研究了其他两个类似的问题和答案,但它们与我的问题不同,我的问题以[,]作为分隔符,其他两个问题具有空格字符作为分隔符,并且我的问题中也存在空格这会使问题变得很复杂,因此,如果我使用该答案,它将无法正常工作,请不要将其标记为重复项。

After some research and test, I found the answer, here is some sample code : 经过研究和测试,我找到了答案,这是一些示例代码:

String str="John,White,\"Some-Company, Inc.\",\"Network Manager, Architect\",xyz@abc.com,,,";
Vector<String> v=new Vector<String>(8);
for (int i=0;i<8;i++) v.add("");

String regex="\"([^\"]*)\"|([^,\\s][^\\,]*[^,\\s]*)";
m=Pattern.compile(regex).matcher(str);
int index=0;
while (m.find())
{
  if (m.group(1) != null) v.set(index,"Quoted [" + m.group(1) + "]");
  else v.set(index," Plain [" + m.group(2) + "]");
  index++;
}
for (int i=0;i<v.size();i++) System.out.println("<"+(i+1)+"> "+v.elementAt(i));

Since I also have to consider some empty items at the end, I set the size of the vector to 8, and set each one to an empty space as place holder. 由于最后我还必须考虑一些空白项,因此我将向量的大小设置为8,并将每个项都设置为一个空白空间作为占位符。

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

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