我有一串
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正则表达式如何实现?
您可以使用此正则表达式:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句