Skip to content
Advertisement

Find passwords values in JSON objects using Regex

I have a big JSON object which contains a lot of different JSON, most of them have the structure below (key: sometext-v1.password, and value: password for example:

"apps":[
        "settings": [
                    {
                       "name" : "sometext-v1.password-v1",
                       "value" : "myPassword"
                    },
                    ...
                    ...

I want to use Regex to extract all passwords by a name which contains ‘password’ string and its value, but I don’t want to iterate the JSON name by name because this takes a lot of time for processing.

I tried this, but it isn’t working:

String regex = ""*password*":\s*".*?"";

Advertisement

Answer

You can use

String regex = ""name"\s*:\s*"[^"]*password[^"]*",\s*"value"\s*:\s*"([^"]*)";

See the regex demo. Details:

  • "name" – a literal string
  • s*:s* – a : enclosed with optional whitespaces
  • " – a " char
  • [^"]*password[^"]*password enclosed with 0 or more chars other than a "
  • ", – a ", string
  • s* – zero or more whitespaces
  • "value" – a literal text
  • s*:s* – a : enclosed with optional whitespaces
  • " – a " char
  • ([^"]*) – Group 1: any zero or more chars other than ".

See a Java demo:

String s = ""apps":[n        "settings": [n                    {n                       "name" : "sometext-v1.password-v1",n                       "value" : "myPassword"n                    },n                    ...";
String regex = ""name"\s*:\s*"[^"]*password[^"]*",\s*"value"\s*:\s*"([^"]*)";
Matcher m = Pattern.compile(regex).matcher(s);
if (m.find()) {
    System.out.println(m.group(1));
}
// => myPassword
Advertisement