2017-01-03 177 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它,对不对?让我检查一下.. –