malteser
malteser

Reputation: 485

Unable to Split by ":[" in Java

I have 2 nested HashMaps as a String which I am trying to parse.

My String is as follows :

"20:[cost:431.14, Count:19, Tax:86.228"

Therefore I need to Split by ":[" in order to get my key, 20, For some reason I'm not able to do this.

I have tried :

myString.split(":[") and myString.split("\\:[") but neither seem to work.

Can anyone detect what I have wrong here?

Thanks in Advance

Upvotes: 2

Views: 665

Answers (6)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59996

You have to escape the character [ , but not the character : like below:

String str = "20:[cost:431.14, Count:19, Tax:86.228";
String[] spl = str.split(":\\[");

Upvotes: 10

AxelH
AxelH

Reputation: 14572

String.split use regex.

Splits this string around matches of the given regular expression.

You need to escape [ since this is a "reserved" character in regular expresionn, not :

myString.split(":\\[")

Not that you could/should set a limit if you only want the first cell

myString.split(":\\[", 2);

This will return an array of 2 cell, so after the first occurence, it doesn't need to read the rest of the String. (This is not really necessary but good to know).

Upvotes: 6

AxelH
AxelH

Reputation: 14572

Another solution if you just need the key "20" in your String is to substring it to get the part before the delimiter.

String key = myString.substring(0, myString.indexOf(":["));

Upvotes: 0

Basil Battikhi
Basil Battikhi

Reputation: 2668

be noted '[' character is special character in regular expression so you have to make an escape character like \\ str.split(":\\["); and remember the string is immutable so if do you want to use it twice you have to reassign it with split like this String[] spl =str.split(":\\[");

Upvotes: 1

Oneiros
Oneiros

Reputation: 4378

Use Pattern.quote to automatically escape your string

String string = "20:[cost:431.14, Count:19, Tax:86.228";
String[] split = string.split(Pattern.quote(":["));

Upvotes: 3

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59996

Another solution :

Therefore I need to Split by ":[" in order to get my key, 20. For some reason I'm not able to do this.

In this case you can use replaceAll with some regex to get this input so you can use :

String str = "20:[cost:431.14, :[Count:19, Tax:86.228";
String result = str.replaceAll("(.*?):\\[.*", "$1");// output 20

regex demo


If the key is just an integer you can use (\d+):\[ check regex demo

Upvotes: 2

Related Questions