0

I have this string:

{"level": "INFO", "message": "89532154: phone number saved successfully."}

I wanted to extract just the word INFO out.

I have tried ^(\{.{10})(\w*), (?<="level":\s*)"(\w*)"

Other expressions that I have tried doesn't work.

So far, only .* works in Android Studio.

I'm using Android Studio 3.2

Kai
  • 143
  • 1
  • 4
  • 11

2 Answers2

1

This is actually a JSON:

{
  "level": "INFO",
  "message": "89532154: phone number saved successfully."
}

You should be able to get the INFO like this from level:

JSONObject obj = new JSONObject(yourcurrentjson);
String levelOutput = obj.getString("level");

// level output should return the INFO

And this with regex:

Map<String, Integer> map = new HashMap<>();
for (String keyValue: json.split(",")) {
    String[] data = keyValue.split(":");
    map.put(
        data[0].replace("\"", """),
        Integer.valueOf(data[1].trim());
    );
}

And then: map.get(key) for getting integers and this:

String.format("\"%s\"\\s*:\\s*\"((?=[ -~])[^\"]+)\"", id_field)

For getting strings like in your case.

Check this out: https://stackoverflow.com/a/37828403/4409113

ʍѳђઽ૯ท
  • 16,646
  • 7
  • 53
  • 108
  • 1
    Looking at it literally in a straight line so much that I forgot that its a JSON. Thanks for the help! The JSON parser really helps and it makes the code much more readable than the regex. – Kai Oct 03 '18 at 23:23
  • Well yes, I prefer the json parser too. However, you could use GSON too: http://www.jsonschema2pojo.org/ And [here](https://stackoverflow.com/questions/6426642/convert-json-to-pojo). – ʍѳђઽ૯ท Oct 04 '18 at 07:20
1

In your first regex you match INFO in the second capturing group by matching first 10 times any character in the first capturing group.

For as far as I know, Java does not allow a variable length in the lookbehind, so \s* does not work. Instead you could use a quantifier like \\s{0,10}

In this case you are better off using a json parser but if you must use a regex you might use:

(?<=\\{\"level\":\\s{0,10}\")\\w+(?=\")

Java Demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70