Search code examples
javaregexscalajacksonjsonnode

Scala : Select the Jackson JsonNode keys using Regex filter in a json


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.


Solution

  • 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 ?