2016-11-18 31 views
0

我有一個字符串豬袋。以下是一些可能的豬袋格式。什麼是最有效的方法來獲取豬袋串中的元組?

{(Kumar,39)},(Raja, 30), (Mohammad, 45),{(balu,29)} 
{(Raja, 30), (Mohammad, 45),{(balu,29)}} 
{(Raja,30),(Kumar,34)} 

這裏所有被「{}」包圍的東西都是豬皮包。獲取所有元組並將其插入到元組對象中的最有效方法是什麼?元組是由「()」包圍的逗號分隔值。豬袋可以包含豬袋和元組。任何幫助將非常感激。以下是我嘗試過的。看起來很笨拙的做法。

private static void convertStringToDataBag(String dataBagString) { 
    Map<Integer,Integer> openBracketsAndClosingBrackets = new HashMap<>(); 
    char[] charArray = dataBagString.toCharArray(); 
    for (int i=0; i<charArray.length;i++) { 
     if(charArray[i] == '(' || charArray[i] == '{') { 
      int closeIndex = findClosingParen(dataBagString,i); 
      openBracketsAndClosingBrackets.put(i,closeIndex); 
      String subString = dataBagString.substring(i+1,closeIndex); 
      System.out.println("sub string : " +subString); 
      if(!subString.contains("(") || !subString.contains(")") || !subString.contains("{") || !subString.contains("}"))) { 
       //consider this as a tuple and comma split and insert. 
      } 
     } 
    } 
} 

public static int findClosingParen(String str, int openPos) { 
    char[] text = str.toCharArray(); 
    int closePos = openPos; 
    int counter = 1; 
    while (counter > 0) { 
     char c = text[++closePos]; 
     if (c == '(' || c== '{') { 
      counter++; 
     } 
     else if (c == ')' || c== '}') { 
      counter--; 
     } 
    } 
    return closePos; 
} 

回答

1

這應該爲你工作:

public static void main(String[] args) throws Exception { 
    String s = "{(Kumar,39)},(Raja, 30), (Mohammad, 45),{(balu,29)}"; 
    // Create/compile a pattern that captures everything between each "()" 
    Pattern p = Pattern.compile("\\((.*?)\\)"); 
    //Create a matcher using the pattern and your input string. 
    Matcher m = p.matcher(s); 
    // As long as there are matches for that pattern, find them and print them. 
    while(m.find()) { 
     System.out.println(m.group(1)); // print data within each "()" 
    } 
} 

O/P:

Kumar,39 
Raja, 30 
Mohammad, 45 
balu,29 
相關問題