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:
JavaScript
x
"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:
JavaScript
String regex = ""*password*":\s*".*?"";
Advertisement
Answer
You can use
JavaScript
String regex = ""name"\s*:\s*"[^"]*password[^"]*",\s*"value"\s*:\s*"([^"]*)";
See the regex demo. Details:
"name"
– a literal strings*:s*
– a:
enclosed with optional whitespaces"
– a"
char[^"]*password[^"]*
–password
enclosed with 0 or more chars other than a"
",
– a",
strings*
– zero or more whitespaces"value"
– a literal texts*:s*
– a:
enclosed with optional whitespaces"
– a"
char([^"]*)
– Group 1: any zero or more chars other than"
.
See a Java demo:
JavaScript
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