Search code examples
regexshellpcre

PCRE RegEx when after "status" something different than "OK"


Those are my health endpoints with JSON:

{
  "JMS Server": {
    "message": "Successfully connected to JMS Server",
    "status": "OK"
  },
  "Database": {
    "message": "Database was successfully reached in 1ms",
    "status": "OK"
  },
  "Application": {
    "message": "IO Error Connection refused (Connection refused)",
    "status": "CRITICAL",
    "info": "URL = http://localhost/testing/healthcheck"
  }
}

and

{
  "JMS Server": {
    "message": "Successfully connected to JMS Server",
    "status": "OK"
  },
  "Database": {
    "message": "JDBC Connection failure",
    "status": "CRITICAL",
    "info": "No operations allowed after connection closed."
  },
  "Application": {
    "message": "Application is up",
    "status": "OK",
    "info": "Application name = Testing"
  }
}

I need a PCRE RegEx when after "status" something different than "OK". I am not sure that there is always written "CRITICAL".

I search with DuckDuckGo for not operator but it never worked with Regexr


Solution

  • @Jan argument is valid. JSON should never be parsed using Regular Expressions. But we might see this requirement an exception if it will not happen for us to have to deal with a more complicated syntax (not pretty the same, more inner objects, arrays, different scalar types etc) and much more domain of including characters.

    If you are sure about all these preconditions then the following regex will match a key/value pair that satisfies your requirements:

    (?m)^[^{}]*{\s*(?>"(?!status": "OK)[^{}"]++)+}
    

    See live demo here