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.

2
  • The regex pattern should look something like """a(\[[0-9]\])?\.b(\[[0-9]\])?\.c(\[[0-9]\])?\.d(\[[0-9]\])?\.e(\[[0-9]\])?""".r. Commented Apr 9, 2021 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. Commented Apr 10, 2021 at 1:16

1 Answer 1

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 ?

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, this too worked, thanks a lot :) I will embed the regex in my main code, if i face any issues, will come back again :) Thank you so very much :)
Shouldn't the closing square brackets be escaped as well?
@TestMirror not needed if the first one is escaped, but you can do it for more clarity of course

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.