2015-06-23 79 views
3

我知道這可能是另一個有關正則表達式的主題,但儘管我搜索了它,但我無法得到明確的答案。因此,這裏是我的problem-我有一個這樣的字符串:用不包含括號的逗號分割,跳過其中的任何內容

{1,2,{3,{4},5},{5,6}} 

我去除最外面的括號(他們是從那裏輸入,我不需要他們),所以現在我有這樣的:

1,2,{3,{4},5},{5,6} 

而現在,我需要把這個字符串分割成元素的數組,治療這些括號內的一切,一個「無縫」的元素:

Arr[0] 1 
Arr[1] 2 
Arr[2] {3,{4},5} 
Arr[3] {5,6} 

我試圖用超前這樣做,但到目前爲止,我失敗了克(悲慘地)。用正則表達式處理這些事情的最好方法是什麼?

回答

0

找不到regex解決方案,但這裏是非regex解決方案。它涉及在每個逗號之前解析數字(不包括大括號)(除非它是字符串中的最後一個數字)並且解析字符串(使用大括號)直到找到組的最後一個大括號。

如果找到正則表達式的解決方案,我很樂意看到它。

public static void main(String[] args) throws Exception { 
    String data = "1,2,{3,{4},5},{5,6},-7,{7,8},{8,{9},10},11"; 
    List<String> list = new ArrayList(); 
    for (int i = 0; i < data.length(); i++) { 
     if ((Character.isDigit(data.charAt(i))) || 
      // Include negative numbers 
      (data.charAt(i) == '-') && (i + 1 < data.length() && Character.isDigit(data.charAt(i + 1)))) { 
      // Get the number before the comma, unless it's the last number 
      int commaIndex = data.indexOf(",", i); 
      String number = commaIndex > -1 
        ? data.substring(i, commaIndex) 
        : data.substring(i); 
      list.add(number); 
      i += number.length(); 
     } else if (data.charAt(i) == '{') { 
      // Get the group of numbers until you reach the final 
      // closing curly brace 
      StringBuilder sb = new StringBuilder(); 
      int openCount = 0; 
      int closeCount = 0; 
      do { 
       if (data.charAt(i) == '{') { 
        openCount++; 
       } else if (data.charAt(i) == '}') { 
        closeCount++; 
       } 
       sb.append(data.charAt(i)); 
       i++; 
      } while (closeCount < openCount); 
      list.add(sb.toString()); 
     } 
    } 

    for (int i = 0; i < list.size(); i++) { 
     System.out.printf("Arr[%d]: %s\r\n", i, list.get(i)); 
    } 
} 

結果:

Arr[0]: 1 
Arr[1]: 2 
Arr[2]: {3,{4},5} 
Arr[3]: {5,6} 
Arr[4]: -7 
Arr[5]: {7,8} 
Arr[6]: {8,{9},10} 
Arr[7]: 11 
+0

有**無** [標籤:正則表達式]溶液,語言[上下文無關(https://en.wikipedia.org /維基/上下文free_language)。 – ShellFish

+0

你好,我有這個代碼的問題 - 我怎麼能使它與負值的工作 - 它要麼刪除減號,要麼沒有它返回的一切。我確信可以快速修復它,但我無法找到它。 – uacnix

+0

@uacnix查看更新後的答案 – Shar1er80

3

如果像這樣的元素應該放在一起,則不能這樣做:{{1},{2}}。原因是這個這相當於解析平衡括號語言。該語言是上下文無關的,不能使用正則表達式進行分析。處理這個問題的最好方法不是使用正則表達式,而是使用for循環與堆棧(該堆棧提供解析上下文無關語言的能力)。在僞代碼,我們可以這樣做:

for char in input 
    if stack is empty and char is ',' 
     add substring(last, current position) to output array 
     last = current index 
    if char is '{' 
     push '{' on stack 
    if char is '}' 
     pop from stack 

根據需要這個僞代碼將構建陣列,請注意,這是最好的循環在給定字符串中的字符的索引,你將需要這些來確定邊界的子串添加到數組中。

1

幾乎接近要求。時間不多了。稍後會完成休息(單個逗號不正確)。
正則表達式:,(?=[^}]*(?:{|$))
要檢查的正則表達式的有效性:轉到http://regexr.com/

enter image description here

使用Java實現這種模式,有一個細微的差別。 \需要在{和}之前添加。

因此,正則表達式的Java輸入:,(?=[^\\}]*(?:\\{|$))

String numbers = {1,2,{3,{4},5},{5,6}}; 
numbers = numbers.substring(1, numbers.length()-1); 
String[] separatedValues = numbers.split(",(?=[^\\}]*(?:\\{|$))"); 
System.out.println(separatedValues[0]); 
相關問題