-1

I have a string:

str = "99,{b:["a1":"0","s1":"0"],c:[{"a2":"0","s2":"0"}]},-98,97,[11,22,33],96,-95,{"b2":"3"}"

I want to split it as below:

v1= 99
v2 = {b:["a1": "0", "s1": "0"],c:[{"a2": "0", "s2": "0"}]}
v3 = -98
v4 = 97
v5 = [11,22,33]
v6 = 96
v7 = -95
v8 = {"b2":"3"}

I have this regex to get the contents of v2:

str[/\{.*?\}]}/]

but I cannot get the other content details.

sawa
  • 165,429
  • 45
  • 277
  • 381
Ravi
  • 211
  • 3
  • 11
  • 5
    Please edit so you have valid Ruby objects for variables that equal strings: `v1="a"`, `v3-"d"`, and so on. Also, you need `str = 'a,{...g' (single quotes) or escape the double quotes within the string. – Cary Swoveland Aug 29 '18 at 01:19
  • Your string in not a valid Ruby object. – sawa Aug 29 '18 at 05:31
  • Hi Sawa, this is the reason why I post this here and this is not an object but a valid string. – Ravi Aug 29 '18 at 14:30
  • No, it is not, it is a `SyntaxError`. – Jörg W Mittag Aug 29 '18 at 21:09
  • Hi Jorg/sawa, This is where the challenge is. I'm trying to give a meaning to the scrap data that we're getting from the 3rd party and I just don't wish to reply that this is not a ruby object or it's a syntax error. sometimes we need to think outside of the box to solve some problems. agree? not sure what you guys found wrong in my question. – Ravi Aug 30 '18 at 16:01

1 Answers1

1

Assuming you have a valid, single-quoted string, here's an option that works for your test input but may run into trouble with nesting, which regex has difficulty matching.

str = '99,{b:["a1":"0","s1":"0"],c:[{"a2":"0","s2":"0"}]},-98,97,[11,22,33],96,-95,{"b2":"3"}'

puts (str.split(/,(?![^\[]*\])/).inject([]) do |a, e|
  if e.count("{") < e.count("}")
    a[-1] += "," + e
  else
    a << e
  end
  a
end)

Output:

99
{b:["a1":"0","s1":"0"],c:[{"a2":"0","s2":"0"}]}
-98
97
[11,22,33]
96
-95
{"b2":"3"}

The idea here is to do a regex split on any commas not inside brackets using a negative lookahead, then combine any hashes that have extra }s with the rest of their structure.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • wow!! that worked. but I'm still trying to understand what's going on in these simple 8 lines of code. Thanks a lot !! – Ravi Aug 29 '18 at 02:21
  • 1
    Sure, glad it worked. It's a bit of a hack because I'm pretty sure there's a regex-only solution. I can post a regex breakdown if that helps. – ggorlen Aug 29 '18 at 02:35
  • 1
    Kat, this works? You show `v2` and `v8` set equal to hashes and `v5` set equal to an array. This answer computes only strings. – Cary Swoveland Aug 29 '18 at 04:49
  • Or maybe not, since the snippet isn't valid JSON (array with keys?). – ggorlen Aug 29 '18 at 05:21
  • Thank you Cary and Ggornel, The above solution worked for me. After the string is split into values I'm parsing the JSON for v2, v8. I mean each value is handled independently. – Ravi Aug 29 '18 at 14:29