Best way to parse this string in java?

I have a line that is a form:

{'var1':var2}

I managed to parse this string so that var1 and var2 are string variables. However, this requires several string token calls, first to divide by ":" and then to retrieve data.

So what would be the best (smallest lines of code) for this?

+3
source share
5 answers

If you need an array containing two values, you can do this in two lines by extracting a substring and then dividing by ":". In the end, it looks something like this:

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

If you really need one line of code, you can combine them into:

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

This should work:

String yourstring = "{'var1':var2}";
String regex = "\\{'(.+)':(.+)}";
Matcher m = Pattern.compile(regex).matcher(yourstring);
String var1 = m.group(1);
String var2 = m.group(2);

EDIT: :

String

{'this is':somestring':more stuff:for you}

:

var1 = this is':somestring
var2 = more stuff:for you

PS: Perl, Java , .

EDIT: , Java regex { unescaped, . .

+2

. , :

case a)

var1 =

:':':

var2 =

':'

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

b) var1 =

:

var2 =

':':':'

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

, " ". / , / .

+2

- ( - . ()):

// 3 lines..
String[] parts = "{'var1':var2}  ".trim().split("':");
String var1 = parts[0].substring(2,parts[0].length);
String var2 = parts[1].substring(0,parts[1].length-1);
+1

:

String re = "\\{'(.*)':(.*)}";
String var1 = s.replaceAll (re, "$1");
String var2 = s.replaceAll (re, "$2");

{, java.util.regex.PatternSyntaxException:

0

All Articles