2012-06-14 96 views
1

我在JAVA中有正則表達式的大概率(花3天!!!)。 這是我的輸入字符串:Java正則表達式嵌套

#sfondo: [#nome: 0, #imga: 0],#111: 222, #p: [#ciccio:aaa, #caio: bbb] 

我需要解析此字符串數組的樹,必須符合這樣的:

group: #sfondo: [#nome: 0, #imga: 0] 
group: #111: 222 
group: #p: [#ciccio:aaa, #caio: bbb] 

用或wythout嵌套括號

我tryed這一點:

"#(\\w+):(.*?[^,\]\[]+.*?),?" 

但是這個組由每個元素分開用「,」也括在括號內TS

回答

0

這似乎爲你工作,例如:

String input = "#sfondo: [#nome: 0, #imga: 0],#111: 222, #p: [#ciccio:aaa, #caio: bbb]"; 
    String regex = "#\\w+: (\\[[^\\]]*\\]|[^\\[]+)(,|$)"; 
    Pattern p = Pattern.compile(regex); 
    Matcher matcher = p.matcher(input); 
    List<String> matches = new ArrayList<String>(); 
    while (matcher.find()) { 
     String group = matcher.group(); 
     matches.add(group.replace(",", "")); 
    } 

編輯:
這隻適用於一個的嵌套深度。使用正則表達式無法處理任意深度的嵌套結構。有關詳細解釋,請參閱this答案。

+0

謝謝lot.This工作的偉大,但不能嵌套括號,如: 「#sfondo:[#nome:0,#imga:0],#111:222, #p:[#ciccio:aaa,#caio:bbb,#ggg:[#fff:aaa]]「(參見:」#ggg「) –

+0

這是正確的: String regex =」(#[^,\\ [\\] +(?:\\?[* \\] +)?)「; –

+0

這不適用於以下字符串: 「#sfondo:[#nome:0,#imga:0],#111:222,#p:[#ciccio:aaa,#ggg:[#fff: aaa],#caio:bbb]「 – Keppil

3

試試這個:

import java.util.regex.*; 

class Untitled { 
    public static void main(String[] args) { 
    String input = "#sfondo: [#nome: 0, #imga: 0],#111: 222, #p: [#ciccio:aaa, #caio: bbb]"; 
    String regex = "(#[^,\\[\\]]+(?:\\[.*?\\]+,?)?)"; 
    Pattern pattern = Pattern.compile(regex); 
    Matcher matcher = pattern.matcher(input); 

    while (matcher.find()) { 
     System.out.println("group: " + matcher.group()); 
    } 
    } 
} 
+0

太棒了! 這是我看到的,我沒有貪婪的話... –

+0

小豁免: 結果:#p:[#ciccio:aaa,#caio:bbb,#ggg:[#fff:aaa] shuld be:#p:[#ciccio:aaa,#caio:bbb,#ggg:[#fff:aaa]] –

+0

在我的回答中看到更新後的代碼,我稍微修改了它 – ioseb