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

0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Well yes, I prefer the json parser too. However, you could use GSON too: jsonschema2pojo.org And here.
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

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.