2017-01-03 224 views
1

我已經查看了大多數正則表達式問題,並且沒有匹配我的具體情況。用圓括號分割字符串,用圓括號分組,

說我有一個字符串:"ABe(CD)(EF)GHi"

我想:"A", "Be", "(CD)", "(EF)", "G", "Hi"

我曾嘗試:

.split("(?=[A-Z\\(\\)])"), which gives me: "A", "Be", "(", "C", "D", ")", "(", "E", "F", ")", "G", "Hi". 

任何想法?

回答

5

試試這個:

String input = "ABe(CD)(EF)GHi"; 

String[] split = input.split("(?=[A-Z](?![^(]*\\)))|(?=\\()|(?<=\\))"); 
System.out.println(Arrays.toString(split)); 

輸出

[A, Be, (CD), (EF), G, Hi] 

解釋

(?=    Before: 
    [A-Z]   Uppercase letter 
    (?![^(]*\))  not followed by ')' without first seeing a '(' 
         i.e. not between '(' and ')' 
) 
|(?=    or before: 
    \(    '(' 
) 
|(?<=    or after: 
    \)    ')' 
) 
+0

這個工作。謝謝:) – w1drose

0

試試這個..

String array = "ABe(CD)(EF)GHi"; 
int i = 0; 

for(int j=0; j<array.length();) 
{ 
    if(Character.isUpperCase(array.charAt(i))) 
    { 
     j++; 
     System.out.println(array.substring(i, i+1)); 
     if(Character.isUpperCase(array.charAt(i+1))) 
     { System.out.println(array.substring(i+1, i+3)); 
      i = i+3; 
      j = j + 3; 
     } 
    } 
    else 
    { 
     System.out.println(array.substring(i+1, i+3)); 
     i = i+4; 
     j = j + 3; 
    } 
} 
+0

請解釋一下你的代碼 – Saveen

0

做匹配而不是拆分。

String s = "ABe(CD)(EF)GHi"; 
Pattern regex = Pattern.compile("\([^()]*\)|[A-Z][a-z]+|[A-Z]"); 
Matcher matcher = regex.matcher(s); 
while(matcher.find()){ 
     System.out.println(matcher.group(0)); 
} 

DEMO

+0

@WiktorStribiżew有人關閉與dupe相同的問題:-) –

+0

所以,你不能repoen它,對不對?讓我檢查一下.. –