这似乎与理智的输入非常有效。我没有测试过奇怪的。
public static void main(String args[]) {
ArrayList<String> split = split("(content4(content3(content2(content1...))))");
System.out.println("Split: " + split);
}
// Standard set of braces.
private static final String openBraces = "({[<";
// Matching close set.
private static final String closeBraces = ")}]>";
public static ArrayList<String> split(String s) {
// Default to splitting with my standard set of braces.
return split(s, openBraces, closeBraces);
}
// Holds the start of an element and which brace started it.
private static class Start {
// The brace number from the braces string in use.
final int brace;
// The position in the string it was seen.
final int pos;
// Constructor.
public Start(int brace, int pos) {
this.brace = brace;
this.pos = pos;
}
@Override
public String toString() {
return "{"+openBraces.charAt(brace)+","+pos+"}";
}
}
public static ArrayList<String> split(String s, String open, String close) {
// The splits.
ArrayList<String> split = new ArrayList<String>();
// The stack.
ArrayList<Start> stack = new ArrayList<Start>();
// Walk the string.
for (int i = 0; i < s.length(); i++) {
// Get the char there.
char ch = s.charAt(i);
// Is it an open brace?
int o = open.indexOf(ch);
// Is it a close brace?
int c = close.indexOf(ch);
if (o >= 0) {
// Its an open! Push it.
stack.add(new Start(o, i));
} else if ( c >= 0 && stack.size() > 0 ) {
// Pop (if matches).
int tosPos = stack.size() - 1;
Start tos = stack.get(tosPos);
// Does the brace match?
if ( tos.brace == c) {
// Matches!
split.add(s.substring(tos.pos, i+1));
// Done with that one.
stack.remove(tosPos);
}
}
}
return split;
}
印刷:
Split: [(content1...), (content2(content1...)), (content3(content2(content1...))), (content4(content3(content2(content1...))))]