0

I'm looking for a simpler solution. I'm new to Java and I need a little help. I'm trying to split String to String[] by this '],['. The problem is that Java tries to get these like a Regex and I don't want to use it because I'm not good enough in it. I want just to split the string by these 3 characters "],["; Here is my code:

String usefulData = ...;
String[] list = null;
String token = "],[";
list = usefulData.split(token);

And here is the error ouput: Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Unclosed character class near index 2 ],[... Please, any suggestions how to make this think works?

PS. Is there any other way to split the String? I don't like this Regex very much. I have been used Qt and C# and in both places there is a way to escape from this Regular Expresions. Thanks a lot People!

2
  • I assume you're parsing something like [a],[b]? In this case the split out result would look like ["[a", "b]"]. Is this what you want? Commented Oct 15, 2012 at 20:45
  • @DonAngelo. Remember to accept one of the answers, by clicking the arrow besides each answer.. Commented Oct 15, 2012 at 21:09

3 Answers 3

5

You want "\]\,\[".

String usefulData = ...;
String[] list = usefulData.split("\\],\\[");

This is because [ and ] are special characters in a RegEx. You have to escape them with \\ to use them as regular characters.

Sign up to request clarification or add additional context in comments.

Comments

4

You can build your String using Pattern#quote method.

That way you won't have to escape your special characters with a backslash. Pattern.quote makes all your special characters in string behave like String literal: -

String usefulData = "[a],[b],[c,d]";
String token = Pattern.quote("],[");
String[] list = usefulData.split(token);

for (String val: list) {
    System.out.println(val.replaceAll("\\[|\\]", ""));
}

OUTPUT: -

a
b
c,d

4 Comments

Thanks for sharing this, I've always escaped myself.
@LanguagesNamedAfterCofee Lol. :) Now you don't have to. Just quote yourself when needed ;)
@DonAngeloAnnoni.. Hello Don. You can try out my updated code. I have added code to remove [ and ] from start and end.
@DonAngeloAnnoni.. Using Regex for this kind of work is far better than using substring, while loop and all that stuff that is in the answer you marked.
2
String usefulData = ...;
String[] list = null;
String token = "],[";
list = usefulData.split(java.util.regex.Pattern.quote(token));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.