0

I have the following json document:

{  
   "videoUrl":"",
   "available":"true",
   "movie":{  
      "videoUrl":"http..."
   },
   "account":{  
      "videoUrl":"http...",
      "login":"",
      "password":""
   }
}   

In this json I have a property named videoUrl, I want to get first non empty videoUrl

My regex:

("videoUrl":)("http.+")

But this regex match the following String

    "videoUrl" :"http..."},
"account" : {"videoUrl" : "http...","login" : "","password" : ""

What is my way to write Regex that will find first non empty videoUrl with it's value

(Result should be "videoUrl":"http...")

5
  • 6
    I don't think you need any regex but json parsing and logic Commented May 23, 2018 at 10:48
  • try adding \s (whitespace) at the end of your expression. Commented May 23, 2018 at 10:48
  • @JanOssowski Thank for response, I add , but still it's not correct Commented May 23, 2018 at 10:50
  • @B001ᛦ The problem is that I dont have i json in the begging, I parse .js script which include this json as part of the code Commented May 23, 2018 at 10:51
  • 1
    Parsing json by regex is not a good idea. Could you try jsonPath? github.com/json-path/JsonPath Commented May 23, 2018 at 10:52

2 Answers 2

4

Add (?!,) at the end of the regex, it will make the regex stop at an , without capturing it:

public static void main(String[] args) {
    String input = "{  \n" +
            "   \"videoUrl\":\"\",\n" +
            "   \"available\":\"true\",\n" +
            "   \"movie\":{  \n" +
            "      \"videoUrl\":\"http...\"\n" +
            "   },\n" +
            "   \"account\":{  \n" +
            "      \"videoUrl\":\"http...\",\n" +
            "      \"login\":\"\",\n" +
            "      \"password\":\"\"\n" +
            "   }\n" +
            "} ";

    Pattern pattern = Pattern.compile("(\"videoUrl\":)(\"http.+\")(?!,)");
    Matcher matcher = pattern.matcher(input);
    while (matcher.find()) {
        System.out.println(matcher.group());  // "videoUrl":"http..."
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

It will be more appropriate to use one of JSON parsers, like Gson or Jackson, instead of regex. Something like:

String jsonStr = "...";
Gson gson = new Gson();
JsonObject json = gson.fromJson(jsonStr, JsonObject.class);
String url = element.get("videoUrl").getAsString();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.