user793491
user793491

Reputation: 193

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?

Upvotes: 3

Views: 1281

Answers (5)

m0skit0
m0skit0

Reputation: 25873

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: for the commentators:

String:

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

Output:

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

PS: tested with Perl, don't have Java at hand right now, sorry.

EDIT: looks like Java regex engine does not like { unescaped as user unknown points out. Escaped it.

Upvotes: 2

user unknown
user unknown

Reputation: 36229

You can use regex:

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

You need to mask the opening {, else you get an java.util.regex.PatternSyntaxException: Illegal repetition

Upvotes: 0

esej
esej

Reputation: 3059

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.

Upvotes: 2

TEOUltimus
TEOUltimus

Reputation: 184

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("':");

Upvotes: 4

Andrew Thompson
Andrew Thompson

Reputation: 168825

Something like (fragile - see comment(s)):

// 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);

Upvotes: 1

Related Questions