我在这里查看了大多数正则表达式的问题,但没有一个与我的具体情况相符。
说我有一个字符串:"ABe(CD)(EF)GHi"
我想:"A", "Be", "(CD)", "(EF)", "G", "Hi"
我试过了:
.split("(?=[A-Z\\(\\)])"), which gives me: "A", "Be", "(", "C", "D", ")", "(", "E", "F", ")", "G", "Hi".
有什么想法吗?
答案 0 :(得分: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:
\) ')'
)
答案 1 :(得分: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;
}
}
答案 2 :(得分: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));
}