0

I am trying to tokenize a jsonpath string. For example, given a string like the following:

$.sensor.subsensor[0].foo[1][2].temp

I want ["$", "sensor", "subsensor", "0", "foo", "1", "2", "temp"]

I am terrible with regexs but I managed to come up with the following which according to regexr matches "." and "[" and "]". Assume the jsonpath string does not contain slices, wildcards, unions nor recursive descent.

[\.\[\]]

I am planning to match all "." and "[" and "]" chars and replace them with ";". Then i will split on ";".

The problem with the above regex is that I will get in certain instances ";;".

$;sensor;subsensor;0;;foo;1;;2;;temp

Is there a way I can in a single regex replace ".", "[", "]" as well as ".[" and "]." or "][" with ";"? Do I need to check for these groups explicitly or do I need to run the sequence through 2 regexs?

Jeremy Fisher
  • 2,510
  • 7
  • 30
  • 59

3 Answers3

2

No needs to transform .[] into ;, just split directly:

console.log('$.sensor.subsensor[0].foo[1][2].temp'.split(/[.[\]]+/));
Toto
  • 89,455
  • 62
  • 89
  • 125
  • can you explain how this works? That regex doesn't look global and it's not escaping the "." or "[" character – Jeremy Fisher Aug 21 '19 at 17:25
  • @JeremyFisher: 1) The global flag is superfluous when spliting. 2) dot and openning square bracket don't need to be escaped within a character class. This is spliting on 1 or more any of `.`, `[` or `]` – Toto Aug 21 '19 at 18:56
  • This is really the best answer. Better if Toto's explanation were moved to the answer from the comment. – Booboo Aug 21 '19 at 19:29
1

You can use this code to omit double semicolon:

console.log(
'$.sensor.subsensor[0].foo[1][2].temp'.replace(/[\.\[\]]+/g, ';')
)
Long Nguyen Duc
  • 1,317
  • 1
  • 8
  • 13
0

Got a decent solution.

/(\.|\].|\[)/g

Apparently when you use [] as part of your regex that matches only a single character, which is why groups like "]." become ";;". Using () allows you to specify character groups, and the above group just enumerates the possibilities.

Jeremy Fisher
  • 2,510
  • 7
  • 30
  • 59