正则表达式:按逗号分割,但括号和引号内不包括逗号(单和双) [英] Regex : Split on comma , but exclude commas within parentheses and quotes(Both single & Double)

查看:73
本文介绍了正则表达式:按逗号分割,但括号和引号内不包括逗号(单和双)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只有一个字符串

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

我想用逗号分割它,但需要在括号和引号(单引号和双引号)中排除逗号.

I want to split it on comma but need to exclude commas within parentheses and quotes(Both single and double quotes).

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

使用Java正则表达式如何实现?

Using java Regular Expression how to achieve this ??

推荐答案

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

You can use this regex:

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

这篇关于正则表达式:按逗号分割,但括号和引号内不包括逗号(单和双)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆