woopi
woopi

Reputation: 13

Regex split by ":{ in java?

basically I have:

 String str = "Stream: {"stream":null,"_links":{"self":"https://api.twitch.tv/kraken/streams/tfue","channel":"https://api.twitch.tv/kraken/channels/tfue"}}";

I want to split the str by ":{ but when I do:

String[] BuftoStringparts = BuftoString.split("\":{");

I get below exception:

java.util.regex.PatternSyntaxException: Illegal repetition near index 1 ":{ ^

All replies are much appreciated :)

Upvotes: 0

Views: 73

Answers (2)

Kaushal28
Kaushal28

Reputation: 5565

First of all you need to escape " in your JSON String, so the resulting String will be:

 String str = "Stream: {\"stream\":null,\"_links\":{\"self\":\"https://api.twitch.tv/kraken/streams/tfue\",\"channel\":\"https://api.twitch.tv/kraken/channels/tfue\"}}";

Now as mentioned by others, you also need to escape regex special characters in your regex. You can try your split by following regex:

String[] BuftoStringparts = BuftoString.split("\":\\{");

Upvotes: 0

Jonathan JOhx
Jonathan JOhx

Reputation: 5968

The main reason this happens:

java.util.regex.PatternSyntaxException: Illegal repetition near index 1 ":{ ^

It's because they are special characters in Java regular expressions so you need to use it escaped for the regex, so by following way:

String[] BuftoStringparts = BuftoString.split("\":\\{");

Upvotes: 1

Related Questions