2014-02-07 3 views
1

나는 이러한 형식의 문자열을 가지고 ?분할 재귀 그룹

+4

아마 쉽게 (그리고 가능 될 가능성이) 정규식없이. – Jerry

+5

이것은 정규식이 아닙니다. 직접 해석하십시오. –

+0

그렇게 생각합니다. 감사. – mortenoh

답변

1

스택을 사용할 때 가능한 해결책은 다음과 같습니다. (Avlin 이층의 의견을 구현했습니다.)

public static Iterable<String> split(String s) { 
    List<String> result = new LinkedList<String>(); 
    Stack<String> stack = new Stack<String>(); 
    Pattern pattern = Pattern.compile("[,\\[\\]]|.+?"); 
    Matcher matcher = pattern.matcher(s); 

    stack.push(""); 
    while (matcher.find()) { 
     String token = matcher.group(); 
     if (token.equals("[")) { 
      stack.push(""); 
     } else if (token.equals("]")) { 
      if (! stack.peek().isEmpty()) 
       result.add(join(".", stack)); 
      stack.pop(); 
      stack.pop(); 
      stack.push(""); 
     } else if (token.equals(",")) { 
      if (! stack.peek().isEmpty()) 
       result.add(join(".", stack)); 
     } else { 
      stack.pop(); 
      stack.push(token); 
     } 
    } 
    if (! (stack.isEmpty() || stack.peek().isEmpty())) 
     result.add(join(".", stack)); 
    return result; 
} 

public static String join(String sep, Iterable<String> it) { 
    // Return it[0] + sep + it[1] + sep + .... + it[lastIndex] 
    String joined = ""; 
    boolean first = true; 

    for (String s : it) { 
     if (first) 
      first = false; 
     else 
      joined += sep; 
     joined += s; 
    } 
    return joined; 
} 

사용 예 :

String text = "a,b,c[a,b,c[a]],d"; 
for (String s : split(text)) 
    System.out.println(s); 

Demo run를 참조하십시오.

(Same solution in Python, Recursive solution in Python)