在引号外用逗号分隔

Jak*_*sen 48 java regex string split

我的程序从文件中读取一行.这一行包含逗号分隔的文本,如:

123,test,444,"don't split, this",more test,1
Run Code Online (Sandbox Code Playgroud)

我想分裂的结果是这样的:

123
test
444
"don't split, this"
more test
1
Run Code Online (Sandbox Code Playgroud)

如果我使用String.split(","),我会得到这个:

123
test
444
"don't split
 this"
more test
1
Run Code Online (Sandbox Code Playgroud)

换句话说:子字符串中的逗号"don't split, this"不是分隔符.怎么处理这个?

在此先感谢..雅各布

Roh*_*ain 106

你可以试试这个正则表达式:

str.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
Run Code Online (Sandbox Code Playgroud)

这会拆分字符串,,然后是偶数个双引号.换句话说,它在双引号之外的逗号上拆分.如果你的字符串中有平衡的引号,这将有效.

说明:

,           // Split on comma
(?=         // Followed by
   (?:      // Start a non-capture group
     [^"]*  // 0 or more non-quote characters
     "      // 1 quote
     [^"]*  // 0 or more non-quote characters
     "      // 1 quote
   )*       // 0 or more repetition of non-capture group (multiple of 2 quotes will be even)
   [^"]*    // Finally 0 or more non-quotes
   $        // Till the end  (This is necessary, else every comma will satisfy the condition)
)
Run Code Online (Sandbox Code Playgroud)

您甚至可以在代码中使用(?x)修饰符和正则表达式进行类似的操作.修饰符忽略了正则表达式中的任何空格,因此更容易读取分为多行的正则表达式,如下所示:

String[] arr = str.split("(?x)   " + 
                     ",          " +   // Split on comma
                     "(?=        " +   // Followed by
                     "  (?:      " +   // Start a non-capture group
                     "    [^\"]* " +   // 0 or more non-quote characters
                     "    \"     " +   // 1 quote
                     "    [^\"]* " +   // 0 or more non-quote characters
                     "    \"     " +   // 1 quote
                     "  )*       " +   // 0 or more repetition of non-capture group (multiple of 2 quotes will be even)
                     "  [^\"]*   " +   // Finally 0 or more non-quotes
                     "  $        " +   // Till the end  (This is necessary, else every comma will satisfy the condition)
                     ")          "     // End look-ahead
                         );
Run Code Online (Sandbox Code Playgroud)

  • 这么多年过去了,这个答案仍然很有价值! (5认同)
  • 很好的解释 (2认同)

zx8*_*x81 13

当你可以匹配时为什么分裂?

恢复这个问题是因为出于某种原因,没有提到简单的解决方案.这是我们精美紧凑的正则表达式:

"[^"]*"|[^,]+
Run Code Online (Sandbox Code Playgroud)

这将匹配所有所需的片段(请参阅演示).

说明

  • 随着"[^"]*",我们匹配完成"double-quoted strings"
  • 要么 |
  • 我们匹配[^,]+任何不是逗号的字符.

可能的改进是改进交替的字符串侧以允许引用的字符串包括转义引号.

  • 如果您还需要获取空字符串,则此解决方案将不起作用,但是我喜欢它。 (2认同)