hamed hamed - 1 year ago 107
Android Question

substring between two delimiters in java

I have a string as :


<script type="text/javascript">window._timings = {"domLoading": Date.now()}</script>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script type="text/javascript">window._sharedData = {"country_code": "IR", "language_code": "en", "gatekeepers": {"cc": true, "sms": true, "ra": true}, "show_app_install": false, "static_root": "//instagramstatic-a.akamaihd.net/h1", "platform": "web"};</script>
<script src="//instagramstatic-a.akamaihd.net/h1/bundles/en_US_ProfilePage.js/88ce62d41e70.js" type="text/javascript" crossorigin="anonymous"></script>

I just need to extract :

{"country_code": "IR", "language_code": "en", "gatekeepers": {"cc": true, "sms": true, "ra": true}, "show_app_install": false, "static_root": "//instagramstatic-a.akamaihd.net/h1", "platform": "web"}

Need help on this.

Answer Source

In terms of simple string parsing you could use some function like this:

public static String between(String start, String end, String input) {
    int startIndex = input.indexOf(start);
    int endIndex = input.lastIndexOf(end);
    if(startIndex == -1 || endIndex == -1) return input;
    else return input.substring(startIndex + start.length(), endIndex + end.length()).trim();

In that case usage will be the following:

String input = "<head>\n" +
        "\n" +
        "    <script type=\"text/javascript\">window._timings = {\"domLoading\": Date.now()}</script>\n" +
        "\n" +
        "        <meta charset=\"utf-8\">\n" +
        "        <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n" +
        "<script type=\"text/javascript\">window._sharedData = {\"country_code\": \"IR\", \"language_code\": \"en\", \"gatekeepers\": {\"cc\": true, \"sms\": true, \"ra\": true}, \"show_app_install\": false, \"static_root\": \"//instagramstatic-a.akamaihd.net/h1\", \"platform\": \"web\"};</script>\n" +
        "<script src=\"//instagramstatic-a.akamaihd.net/h1/bundles/en_US_ProfilePage.js/88ce62d41e70.js\" type=\"text/javascript\" crossorigin=\"anonymous\"></script>";
System.out.println(between("window._sharedData =", "}", input));

Result is as expected:

{"country_code": "IR", "language_code": "en", "gatekeepers": {"cc": true, "sms": true, "ra": true}, "show_app_install": false, "static_root": "//instagramstatic-a.akamaihd.net/h1", "platform": "web"}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download