![](/img/trans.png)
[英]Java Regex - split comma separated list, but exclude commas within parentheses
[英]Regex : Split on comma , but exclude commas within parentheses and quotes(Both single & Double)
我有一個字符串
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如何實現這個?
你可以使用這個正則表達式:
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
字符串,而是考慮匹配。
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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.