2016-11-18 1 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 
関連する問題