user3214173
user3214173

Reputation: 227

using patterns and matchers

I want to extract Failed from this string {"Login":"Failed"} How do I set the pattern? Also could you provide an explanation. I referred to this site, but didn't understand what they meant by setting the pattern. This is what I tried which failed:

Pattern pattern = Pattern.compile(":");
Matcher matcher = pattern.matcher(login);
if (matcher.find()) {
    System.out.println(matcher.group(1));
}

Upvotes: 1

Views: 62

Answers (4)

user2786437
user2786437

Reputation: 53

String line="{\"Login\":\"Failed\"};
 Pattern pattern = Pattern.compile("Failed");
    Matcher matcher = pattern.matcher(line);
    if (matcher.find()) {
        System.out.println(matcher.group(0));
    }

or you can also use
String line="{\"Login\":\"Failed\"};
 Pattern pattern = Pattern.compile(":\"(\\w+)\"");
    Matcher matcher = pattern.matcher(line);
    if (matcher.find()) {
        System.out.println(matcher.group(1));
    }

Upvotes: 0

Silviu Burcea
Silviu Burcea

Reputation: 5348

Your string is in JSON format. An alternative to RegExp should be to parse it as JSON and then get the property "Login" from the JsonObject.

Recommended library: Google GSON.

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136012

You dont have groups in your regex, group is an expression in parentheses. This task can also be solved with replaceAll

s = s.replaceAll(".+:\"(.+)\"}", "$1");

Upvotes: 0

Nambi
Nambi

Reputation: 12042

Use this Pattern :\"(\\w+)\"

Do like this

public static void main(String args[]){

        String login="{\"Login\":\"Failed\"}";
         Pattern pattern = Pattern.compile(":\"(\\w+)\"");
            Matcher matcher = pattern.matcher(login);
            if (matcher.find()) {
                System.out.println(matcher.group(1));
            }

Upvotes: 1

Related Questions