正则表达式:用逗号分隔,但在括号和引号中排除逗号(单引号和双引号)

时间:2015-02-18 15:19:40

标签: java regex

我有一个字符串

5,(5,5),C'A,B','A,B',',B','A,',"A,B",C"A,B" 

我想将其拆分为逗号,但需要在括号和引号(单引号和双引号)中排除逗号。

喜欢这个

5 (5,5) C'A,B' 'A,B' ',B' 'A,' "A,B" C"A,B"

使用java Regular Expression如何实现这个??

3 个答案:

答案 0 :(得分:4)

您可以使用此正则表达式:

String input = "5,(5,5),C'A,B','A,B',',B','A,',\"A,B\",C\"A,B\"";
String[] toks = input.split( 
                ",(?=(([^']*'){2})*[^']*$)(?=(([^\"]*\"){2})*[^\"]*$)(?![^()]*\\))" );
for (String tok: toks)
    System.out.printf("<%s>%n", tok);

<强>输出:

<5>
<(5,5)>
<C'A,B'>
<'A,B'>
<',B'>
<'A,'>
<"A,B">
<C"A,B">

<强>解释

,                         # Match literal comma
(?=(([^']*'){2})*[^']*$)  # Lookahead to ensure comma is followed by even number of '
(?=(([^"]*"){2})*[^"]*$)  # Lookahead to ensure comma is followed by even number of "
(?![^()]*\\))             # Negative lookahead to ensure ) is not followed by matching
                          # all non [()] characters in between

答案 1 :(得分:2)

,(?![^(]*\))(?![^"']*["'](?:[^"']*["'][^"']*["'])*[^"']*$)

试试这个。

请参阅demo

对于java

,(?![^(]*\\))(?![^"']*["'](?:[^"']*["'][^"']*["'])*[^"']*$)

答案 2 :(得分:2)

而不是split字符串,而是考虑匹配。

String s  = "5,(5,5),C'A,B','A,B',',B','A,',\"A,B\",C\"A,B\"";
Pattern p = Pattern.compile("(?:[^,]*(['\"])[^'\"]*\\1|\\([^)]*\\))|[^,]+");
Matcher m = p.matcher(s);
while (m.find()) {
  System.out.println(m.group());
}

输出

5
(5,5)
C'A,B'
'A,B'
',B'
'A,'
"A,B" 
C"A,B"