使用模式和匹配器

时间:2014-02-12 06:28:46

标签: java regex

我想从此字符串中提取失败{"Login":"Failed"}如何设置模式?你也可以提供一个解释。我提到this site,但是通过设置模式不明白它们的含义。这是我尝试失败的原因:

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

4 个答案:

答案 0 :(得分:1)

使用此模式:\"(\\w+)\"

这样做

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));
            }

答案 1 :(得分:1)

您的字符串是JSON格式。 RegExp的替代方法应该是将其解析为JSON,然后从JsonObject获取属性“Login”。

推荐图书馆:Google GSON。

答案 2 :(得分:0)

你的正则表达式中没有组,组是括号中的表达式。此任务也可以使用replaceAll

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

答案 3 :(得分:0)

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));
    }
相关问题