1

I need help to build a regex rule to find some [ on a text file.

Here is a sample of te text. It is a Json, but I can't use it as it is because of limitation of the program I'm using.

{
    "event":[
        "ONIMBOTMESSAGEADD"
    ],
    "data[BOT][123][BOT_ID]":[
        "123"
    ]
}

I need to find a regex that matches the line "data[BOT][123][BOT_ID]":[ and find all [ on it. The objectve is to replace it by an underscore so I would end up with something like this:

{
    "event":[
        "ONIMBOTMESSAGEADD"
    ],
    "data_BOT_123_BOT_ID":[
        "123"
    ]
}

I can't just remove all special characters because this would destroy the json structure.

I found a way to select each one of the lines that need to be corrected with the rule below, but I was not able to apply another rule over the result. I don't know how to do it.

pattern = (("data\[[a-zA-Z]+]\[[0-9]+]\[([a-zA-Z]+_[a-zA-Z]+)\]":\[)|("data\[[A-Z]+]\[([A-Z]+(_|)[A-Z]+)\]":\[)|("data\[[A-Z]+]\[([A-Z]+(_|)[A-Z]+(_|)[A-Z]+)\]":\[))

Any ideas on how to solve it? Thank you in advance.

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
  • 1
    Parse the JSON, then apply a RegEx to the keys. – Luatic Dec 12 '22 at 19:23
  • That is the problem. I can't parse the Json. I'm using Genexus and It doesn't allows key names like these "data[BOT][123][BOT_ID]" so, it's impossible to parse. I have to remove the problematic characters before doing anithing... – Diego Lopes Penna Dec 12 '22 at 19:29
  • Looks like this Genexus [supports the `\G` anchor](https://wiki.genexus.com/commwiki/servlet/wiki?4606,Regular+Expressions+%28RegEx%29) which lets continue where a previous match ended. It is used to chain matches to some start point. Please check if it the following subsitution works: Replace `(?:\G(?!^)|("data))[\]\[]+([^:"\]\[]*)\]?` with `$1_$2` ([see this regex101 demo](https://regex101.com/r/0eAkAe/3)) – bobble bubble Dec 12 '22 at 21:11

1 Answers1

0

Replacing weird data* key by only data:

jq '.["data"] = .[keys[0]] | del(.[keys[1]])' file
{
  "event": [
    "ONIMBOTMESSAGEADD"
  ],
  "data": [
    "123"
  ]
}
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223