Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to parse this string in java?

I have a string that is the form of:

{'var1':var2}

I was able to parse this string so that var1 and var2 are both string variables. However it takes multiple string tokenizer calls, first to split from the ":" and then to extract the data.

So what would be the best (least lines of code) to do this?

like image 256
user793491 Avatar asked May 15 '26 01:05

user793491


2 Answers

If you just want an array containing the two values, then you can can do it in two lines by extracting a substring and then splitting on "':". It would end up looking something like this:

s = s.substring(2, s.length()-1);
String[] sarr = s.split("':");

If you really wanted a single line of code, you could combine them into:

String[] sarr = s.substring(2, s.length()-1).split("':");
like image 115
TEOUltimus Avatar answered May 16 '26 14:05

TEOUltimus


This is unsolvable in the general case. Consider for example:

case a)

var1=

:':':

var2=

':'

The the full original string would be

{':':':':':'}

case b) var1=

:

var2=

':':':'

the the full original string would be

{':':':':':'}

So, we need "more information". Depending on your requirements / use case you had to live with the ambiguity, put limitations on the strings, or escape/encode the strings.

like image 32
esej Avatar answered May 16 '26 13:05

esej



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!