gpt4 book ai didi

java - 正则表达式 : Split on comma , 但排除括号和引号内的逗号(单双)

转载 作者:行者123 更新时间:2023-12-02 06:57:22 24 4
gpt4 key购买 nike

我有一根绳子

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

关于java - 正则表达式 : Split on comma , 但排除括号和引号内的逗号(单双),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28587081/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com