I have a string like this:
one,two,3,(4,five),six,(seven),(8,9,ten),eleven,(twelve,13,14,fifteen)
the above string should split into:
here you go... :)
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
*
* @author S1LENT W@RRIOR
*/
public class Tokenizer {
public static void main(String... args) {
List tokens = new ArrayList(); // List to store tokens
String string = "one,two,3,(4,five),six,(seven),(8,9,ten),eleven,(twelve,13,14,fifteen)"; // input string
StringTokenizer tokenizer = new StringTokenizer(string, "(),", true); // tokenize your string on the basis of these parentheses
while (tokenizer.hasMoreElements()) { // iterate over tokens
String aToken = (String) tokenizer.nextElement(); // get a token
if (aToken.equals("(")) { // if token is the begining of a parenthisis
StringBuilder sb = new StringBuilder(aToken);
String nextToken = (String) tokenizer.nextElement(); // get next token
while (!nextToken.equals(")")) { // iterate over next tokens untill you find the ending bracket
sb.append(nextToken);
nextToken = (String) tokenizer.nextElement();
}
sb.append(")");
tokens.add(sb.toString()); // add to tokens list
} else if(aToken.equals(",")) { // need this to avoid adding commas
// do nothing
} else {
tokens.add(aToken); // add to tokens list
}
}
for(String aToken: tokens) { // print all tokens
System.out.println(aToken);
}
}
}