0

I'm trying to extract Json value from payload in java code. So I have

"{"object":"page","entry":[{"id":"111111111111111","messaging":[{"sender":{"id":"49783635606516156", "options":"TETX_ARRAY"},"recipient":{"id":"111111111111111"},"message":{"mid":"m_secret","text":"\/start"}}]}]}";

but that also could be

"{"object":"page","entry":[{"id":"111111111111111","messaging":[{"sender":{"options":"TETX_ARRAY", "id":"49783635606516156"},"recipient":{"id":"111111111111111"},"message":{"mid":"m_secret","text":"\/start"}}]}]}";

I need to extract "sender"-"id" value.

I've tried this regex "sender\":.*\"id\":\"([^\"]+)"; (first "id" word after any number of characters after "sender"), but it doesn't work.

What would be correct regex for this?

Thank you!

  • 1
    Артём, use a JSON parser, see [How to parse JSON in Java](https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) for example. – Wiktor Stribiżew Nov 10 '20 at 09:56

1 Answers1

1

If you want to use regex, you could try the following: "sender":.*?"id":"(?<senderId>\d+)"

  • this searches for "sender" ("sender":)
  • then searches for the first occurrence of "id:" after the "sender" (.*?"id":")
  • and finally extracts the value into the named group "senderId" ((?<senderId>\d+))

Example: https://regex101.com/r/UiJZih/1/

Please note that this is quite error prone (just imagine some extra white-spaces in your json which would break the regex). Of course, the regex could be improved further but I guess you will never get all edge-cases.

That being said, you should prefer using a JSON parser to extract the required information.

Thomas D.
  • 1,031
  • 6
  • 17