2013-02-09 57 views
3

我試着寫正則表達式,將拆分Java字符串這樣的內逗號:在Java的正則表達式 - 分裂逗號分隔的列表,但不包括括號

300x250,468x60,300x400v(480x320,768x1024,100x100),400x300v,640x480v(200x200,728x90) 

到這樣的事情:

300x250 
468x60 
300x400v(480x320,768x1024,100x100) 
400x300v 
640x480v(200x200,728x90) 

我一直在嘗試\,(\()?,但最終還是在圓括號中選擇了逗號。

任何幫助表示讚賞!

+0

可能重複的[Java的分裂字符串而忽略括號內的任何分隔符](http://stackoverflow.com/questions/9656212/java-splitting-a-string-while-ignoring-any-delimiters-between-brackets) – jlordo 2013-02-10 00:04:03

+4

@jlor做 - 鏈接的問題是**不是重複**。用戶不會試圖平衡括號 - 只有一層,這完全可以使用正則表達式。 – JDB 2013-02-10 02:41:28

+0

@ Cyborgx37:如果您確定,請發佈正則表達式解決方案。 Stephen C的回答不起作用。 – jlordo 2013-02-10 10:51:02

回答

5

如果你必須使用正則表達式,你可以在,(?![^(]*\\))

分裂如果沒有,那麼一個簡單的迭代超過字符可以做的伎倆

String data="300x250,468x60,300x400v(480x320,768x1024,100x100),400x300v,640x480v(200x200,728x90)"; 

List<String> tokens=new ArrayList<>(); 
StringBuilder buffer=new StringBuilder(); 

int parenthesesCounter=0; 

for (char c : data.toCharArray()){ 
    if (c=='(') parenthesesCounter++; 
    if (c==')') parenthesesCounter--; 
    if (c==',' && parenthesesCounter==0){ 
     //lets add token inside buffer to our tokens 
     tokens.add(buffer.toString()); 
     //now we need to clear buffer 
     buffer.delete(0, buffer.length()); 
    } 
    else 
     buffer.append(c); 
} 
//lets not forget about part after last comma 
tokens.add(buffer.toString()); 

String[] splitedArray=tokens.toArray(new String[tokens.size()]); 

//lets test what is inside our array 
for (String s : splitedArray) 
    System.out.println(s); 

輸出

300x250 
468x60 
300x400v(480x320,768x1024,100x100) 
400x300v 
640x480v(200x200,728x90) 
+0

您的示例輸出非常混亂且具有誤導性。 :)另外,如果它在角色類中,我認爲你不需要逃避開場白。 – JDB 2013-02-10 14:13:37

+0

@ Cyborgx37希望它現在不那麼困惑:) – Pshemo 2013-02-10 15:08:02

+0

好得多。 :) – JDB 2013-02-10 15:50:06

0

akburg,爲了完成這個問題而復活,因爲它有另一個沒有提到的簡單解決方案。這種情況類似於Match (or replace) a pattern except in situations s1, s2, s3 etc

下面是我們簡單的regex:

\([^)]*\)|(,) 

交替的左側匹配完整(parentheses)標籤。我們將忽略這些匹配。右側與第1組匹配並捕獲逗號,並且我們知道它們是正確的逗號,因爲它們與左側的表達式不匹配。

這個程序演示瞭如何使用正則表達式(見成績的online demo的底部):

import java.util.*; 
import java.io.*; 
import java.util.regex.*; 
import java.util.List; 

class Program { 
public static void main (String[] args) throws java.lang.Exception { 

String subject = "300x250,468x60,300x400v(480x320,768x1024,100x100),400x300v,640x480v(200x200,728x90)"; 
Pattern regex = Pattern.compile("\\([^)]*\\)|(,)"); 
Matcher m = regex.matcher(subject); 
StringBuffer b= new StringBuffer(); 
while (m.find()) { 
if(m.group(1) != null) m.appendReplacement(b, "SplitHere"); 
else m.appendReplacement(b, m.group(0)); 
} 
m.appendTail(b); 
String replaced = b.toString(); 
String[] splits = replaced.split("SplitHere"); 
for (String split : splits) System.out.println(split); 
} // end main 
} // end Program 

參考

How to match (or replace) a pattern except in situations s1, s2, s3...

相關問題