0

I have sample jsonNode data - Inputstr =

{
"a.b.c.d.e":"123",
"a[0].b.c.d[0].e":"123",
"a[0].b.c.d[1].e":"123",
"a[1].b.c.d[0].e":"123",
"a[1].b.c.d[1].e":"123",
"d.e.f"="789",
"x.y.z"="789"
}

I want to extract the keys having data in format a[0-9*].b[0-9*].c[0-9*].d[0-9*].e[0-9*]. Basically, the output should return me, 0 or more occurrences

[ a.b.c.d.e , a[0].b.c.d[0].e, a[0].b.c.d[1].e, a[1].b.c.d[0].e, a[1].b.c.d[1].e ].

So, what i did was

val json = ObjectMapper.readTree(Inputstr)
val itr = json.fieldNames

Now on this iterator of keys i want to create a generic regex which returns me the above output.

I tried but not working

val regex = """a\[[0-9\]]*.b\[[0-9\]]*.c\[[0-9\]]*.d\[[0-9\]]*.e\[[0-9\]]*""".r
while(itr.hasNext())
{
    val str= itr.next()
    regex.findAllIn(str)
}

I am stuck in creating the regex basically which can take [0-9]*, it should check for both the braces [ ] as well as presence of a digit from 0 to 9 inside the braces. Even if none exists, it should return me a.b.c.d.e as well.

I hope it makes sense. Please let me know if any questions.

username89
  • 51
  • 7
  • The regex pattern should look something like `"""a(\[[0-9]\])?\.b(\[[0-9]\])?\.c(\[[0-9]\])?\.d(\[[0-9]\])?\.e(\[[0-9]\])?""".r`. – Leo C Apr 09 '21 at 22:48
  • 1
    Just a side note, to ease pattern changes across the segments in the future you could also assemble the regex pattern like `"abcde".map(_ +: "(\\[[0-9]\\])?").mkString("\\.").r`. – Leo C Apr 10 '21 at 01:16

1 Answers1

0

a(?:\[\d])?\.b(?:\[\d])?\.c(?:\[\d])?\.d(?:\[\d])?\.e(?:\[\d])?

Should do the job, I included the [0] part inside of a non matching group that can be optional using ?

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89