"Unclosed character class near index 0" ? [solved]

Long story short, I’m making a class to read text files in a specific way. I’m storing a lot of information about my game (including enemy stats) in text files that I read in and parse appropriately. I am not writing that class, and getting a very biazzare error.

My centralized “parsing” involves taking a string and making two String[] arrays, one that contains everything in square brackets, and one that contains everything outside of square brackets.

For example, this string

NAME: [NAME]
FILE: [FILE]
TYPE: [TYPE1] [TYPE2]
COLOR: [COLOR]
HP: [HP]
PWR: [PWR]
DEF: [DEF]
SPD: [SPD]

Should be parsed, via the method “splitInBrackets” into:

[NAME, FILE, TYPE1, TYPE2, COLOR, HP, PWR, DEF, SD]

Now, when I pass that exact string into my method, I get this error:

Caused by: java.util.regex.PatternSyntaxException: Unclosed character class near index 0
[
^
	at java.util.regex.Pattern.error(Unknown Source)
	at java.util.regex.Pattern.clazz(Unknown Source)
	at java.util.regex.Pattern.sequence(Unknown Source)
	at java.util.regex.Pattern.expr(Unknown Source)
	at java.util.regex.Pattern.compile(Unknown Source)
	at java.util.regex.Pattern.<init>(Unknown Source)
	at java.util.regex.Pattern.compile(Unknown Source)
	at java.lang.String.split(Unknown Source)
	at java.lang.String.split(Unknown Source)

at the line that says “String[] comp = ref.split(”[");"

Why is this happening? (Method code below)

private String[] splitInBrackets(String ref){
		System.out.println(ref);
		String[] comp = ref.split("[");
		//split
		//NAME: [NAME] AGE: [AGE]
		//into
		//|NAME: |NAME] AGE: |AGE]
		//then for each component splits it further to get out the parts in the [ ]
		
		//will throw out of bounds exception if weird stuff isn't formatted with the brackets
		for(int i = 1; i < comp.length; i++){
			String[] dcomp = comp[i].split("]");
			comp[i] = dcomp[0];
		}
		
		return comp;
	}

[icode]String.split(…)[/icode] takes a regex pattern as a parameter. :emo:

I don’t know anything about regex, I’m not gonna lie. But I was under the impression that “split” just returned an array of strings, cutting up your string using the argument as a divider

for example,

“A,B,C,D,E”.split(",") = {“A”, “B”, “C”, “D”, “E”}

And that is actually true

If this ISN’T always the case, then how can I get the behavior I’m looking for?

So, hilariously, you either have to write your own split function, or use the quirky StringTokenizer.

The Sun guys really screwed up with the Java 1.4 String class, but well, you’ll be able to split your string also, using a regex-pattern, which requires double escaping, as Java doesn’t support embedded regex - anyway, you’d end up with: [icode]str.split("\]")[/icode]

:emo:

[icode]String.split("\[");[/icode]

Edit: Ninja’d

That’s very weird. I did not know about that. Now it works though!