-1

I have some string with such format:

    aaaaaaaaaaaa  //first line
    [key = [metadata = 1 metadata = 2 metadata =3] KEY(1) = 100 
KEY(2) = 16:30:00 KEY(3) = 2020-12-12 08:30:30 KEY(4) = 0]

I want to get the key value pairs in Json format like {"KEY(1)":"100", "KEY(2)":"16:30:00", "KEY(3)":"2020-12-12 08:30:30", "KEY(4)":"0"}

I am kind of struggling to deal with the last part, because there could be space also in value like 2020-12-12 08:30:30, so the only way I can think of is to find the "=", the data between the first space and the second space on the left is the current key, and all rest util the previous "=" is the value for previous key, which is tricky. How should I do it?

Dharman
  • 30,962
  • 25
  • 85
  • 135
coder2
  • 37
  • 5
  • Looks like you are looking to create a regex, but do not know where to get started. Please check [Reference - What does this regex mean](https://stackoverflow.com/questions/22937618) resource, it has plenty of hints. Also, refer to [Learning Regular Expressions](https://stackoverflow.com/questions/4736) post for some basic regex info. Once you get some expression ready and still have issues with the solution, please edit the question with the latest details and we'll be glad to help you fix the problem. – Wiktor Stribiżew Oct 13 '20 at 07:35

1 Answers1

-1

I would not try to use a regex to do this.

There are difficulties you haven't considered yet. For example, the quoted string can contain an =, or (worse) it can contain a quote mark, so something like this is unusual, but seems to be legitimate:

{ "\"key\"=\"value\"" = "This is the value"}

When you're done parsing it, the key in this case will be "key" = "value" (with the quote marks and equal sign included in the string.

So not only do you need to recognize the beginning and end of each part of what you're dealing with, but in some cases you need to do some transformations on it to get the correct string.

Now, I'm not going to say this can't be done using a regex--but I think (at best) developing a regex that will work correctly will be more trouble than it's worth.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111