2016-11-18 3 views
0

나는 문자열 돼지 가방이 있습니다. 다음은 돼지 가방 형식 중 일부입니다.pig bag string 내에 튜플을 만드는 가장 효율적인 방법은 무엇입니까?

{(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