這似乎與理智的投入相當不錯的工作。我還沒有測試過奇怪的。
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...))))]
它看起來像一個正常的堆棧probelm對我來說。順便說一下,你的字符串缺少一個'''。 – cwhsu 2013-03-20 15:51:45
恕我直言,正則表達式不合適,簡單遞歸裁剪解析器是要走的路 – 2013-03-20 15:52:26
是否有更多然後一個元素內的零件? – 2013-03-20 15:53:04