【问题标题】:Splitting a string by value between quotation marks in Java在Java中的引号之间按值拆分字符串
【发布时间】:2014-10-23 14:12:36
【问题描述】:

我正在用 Java 读取文件,并希望用引号内的值分割每一行。例如,一行将是...

"100","this, is","a","test"

我希望数组看起来像..

[0] = 100
[1] = this, is
[2] = a
[3] = test

我通常用逗号分隔,但由于某些字段包含逗号(上例中的位置 1),因此不太合适。

谢谢。

【问题讨论】:

  • String.split(String regex) 方法使用正则表达式作为参数,所以只需使用匹配"something" 的正则表达式我不确定但有人会给你答案很快
  • 删除第一个和最后一个 " 字符,然后在 "," 上拆分它
  • 是的,我对他的例子中的逗号有点困惑,我没有第一次看到它

标签: java string split


【解决方案1】:

你可以通过以下方式拆分它:

String input = "\"100\",\"this, is\",\"a\",\"test\"";
for (String s:input.split("\"(,\")*")) {
    System.out.println(s);
}

输出

100
this, is
a
test

注意 第一个数组元素将为空。

【讨论】:

    【解决方案2】:

    您可以执行以下操作

        String yourString = "\"100\",\"this, is\",\"a\",\"test\"";
        String[] array = yourString.split(",\"");
        for(int i = 0;i<array.length;i++)
            array[i] = array[i].replaceAll("\"", "");
    

    最后 array 变量将是所需的数组

    输出:

        100
        this, is
        a
        test
    

    【讨论】:

      【解决方案3】:

      这是一种简单的方法:

      String example = "\"test1, test2\",\"test3\"";
      int quote1, quote2 = -1;
      while((quote2 != example.length() - 1) && quote1 = example.indexOf("\"", quote2 + 1) != -1) {
        quote2 = example.indexOf("\"", quote1 + 1);
        String sub = example.substring(quote1 + 1, quote2); // will be the text in your quotes
      }
      

      【讨论】:

      • 使用比“a”更能说明问题的名称和示例字符串,以便 sn-p 可运行并且您可以提供示例输出,这将是完美的 ;-)
      【解决方案4】:

      这是一种使用正则表达式的方法。

      public static void main (String[] args) {
          String s = "\"100\",\"this, is\",\"a\",\"test\"";
          String arr[] = s.split(Pattern.quote("\"\\w\"")));
          System.out.println(Arrays.toString(arr));
      }
      

      输出:

      ["100","this, is","a","test"]
      

      它的作用是匹配:

       \" -> start by a "
        \\w -> has a word character
        \" -> finish by a "
      

      我不知道你有什么样的价值观,但你可以根据需要进行修改。

      【讨论】:

        【解决方案5】:

        又快又脏,但有效:

            String s = "\"100\",\"this, is\",\"a\",\"test\"";
            StringBuilder sb  = new StringBuilder(s);
            sb.deleteCharAt(0);
            sb.deleteCharAt(sb.length()-1);
            String [] buffer= sb.toString().split("\",\"");
            for(String r : buffer)
                System.out.println(r); code here
        

        【讨论】:

        • 而不是将您的字符串转换为 StringBuilder,您可以在字符串上使用 substring 方法
        • 我虽然想到了这一点,但决定使用像deleteCharAt这样的显式方法更容易理解
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-16
        • 1970-01-01
        • 1970-01-01
        • 2020-02-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多