Ketki Gupta
Ketki Gupta

Reputation: 1

AWS API Gateway Lambda regex not working/ Java

I am trying to match below regular expression for a specific response returned by Lambda function in java. But it does not seem to be working.

Lambda Error Regex -

.*"status:\s"422.*

Lambda error response format(response object is a POJO) -

{
  "id": "3sghsh3232",
  "status": 422,
  "responseCode": "INVALID-DATA",
  "message": "Please provide a valid data",
  "time": "2019-08-30T06:16:20.976",
  "errors": [
    {
      "code": "422",
      "message": "Missing fields"
    }
  ]
}

Tried expressions -

".*\\\"status\\\":422.*"
.*422(.|\n)*
.*422.*

Upvotes: 0

Views: 1747

Answers (2)

Luis Colorado
Luis Colorado

Reputation: 12698

Well, as you will see, your regex is incorrect:

.*"status:\s"422.*
         ^ (look here)
  1. .* matches any string before what follows.
  2. "status:\ " matches literally the sequence of double quotes, the word status, ... beeep (there's a double quote after status, not after the colon and the next space character).

NOTE

Response object is not a POJO (pojo stands for the acronym (P)lain (O)ld (J)ava (O)bject, and what you are posting is, indeed, a JSON encoded string data)


The correct regexp should be (as the data shows):

"status":\s*(\d+),
       ^ (see how we moved the double quotes here)
  1. The .* is not necessary, as any regexp that has no anchor char (^ at the beginning, or $ at the end) matches at any position in the string.
  2. Then follows the string "status": literally.
  3. Then a group \s* of spaces (indeed, tab or spaces, any number, even zero is valid)
  4. Then a group of one or more digits (the parenthesis makes the subexpression to become a group, so you can select only the part matching that group, and get the status value)
  5. Finally, the , comma after all, as everytime the status will be followed by a comma to separate the next field.

See demo.

Upvotes: 1

amittn
amittn

Reputation: 2355

  • I think this should work try it out at regex101
\W*((?i)\"status\"(?-i))\:[\s]+422\,$   
or
\W*((?i)\"status\")\:\s+422\,$
or
\W*(\"status\")\:*\s422\,$
  • \W* matches any non-word character (equal to [^a-zA-Z0-9_])
  • (?i) match the remainder of the pattern with the following effective flags:gmi
  • \" matches the character " literally (case insensitive)
  • \s matches any whitespace character (equal to [\r\n\t\f\v ])
  • \, matches the character , literally (case sensitive)

Upvotes: 1

Related Questions