简体   繁体   English

在逗号上分割字符串,但括号内不分割逗号

[英]split string on comma, but not commas inside parenthesis

Now I have a task about Java IO , I need to read file line by line and save this data into database, But Now I got a problem. 现在我有一个关于Java IO的任务,我需要逐行读取文件并将此数据保存到数据库中,但是现在我遇到了问题。

"desk","12","15","(small,median,large)"

I want to use string.split(",") to split by , and save data into each column. 我想使用string.split(",")进行分割,并将数据保存到每一列中。 But I found that the data in the () has also been split, I do not want to split (small, median, large) and I want to keep this integrity. 但是我发现()中的数据也已拆分,我不想拆分(小,中位数,大),并且我想保持这种完整性。 How can I do that? 我怎样才能做到这一点? I know I can use regualr expression , but I really do not know how to do it? 我知道我可以使用regualr表达式,但是我真的不知道该怎么做?

或者,如果Java必须是:),则可以用“ \\\\ s * \\” \\\\ s *,\\\\ s * \\“”分割,然后在第一个字段的开头和结尾处添加“第二个。我输入\\ s是因为我看到您也有空格分隔符-15“,blank”(小

You could solve this by using Pattern and Matcher . 您可以使用PatternMatcher解决此问题。 Any solution using split would just seem like a nasty workaround. 任何使用split的解决方案似乎都是一个讨厌的解决方法。 Here's an example: 这是一个例子:

public static void main(String[] args){
    String s = "\"desk\",\"12\",\"15\",\"(small,median,large)\"";
    Pattern p = Pattern.compile("\".+?\"");
    Matcher m = p.matcher(s);
    List<String> matches = new ArrayList<String>();

    while (m.find()){
        matches.add(m.group());
    }

    System.out.println(matches);
}
(\(.+?\)|\w+)

the code above matches the result below this will allow for a more flexible solution that some of the other posted ones. 上面的代码与下面的结果相匹配,这将使解决方案比其他已发布的解决方案更加灵活。 The syntax for the regular expression is in another answer on this page just use this regular expression instead 正则表达式的语法在此页的另一个答案中,请改用此正则表达式

desk
12 12
15 15
(small,median,large) (小,中,大)

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

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