2014-02-12 47 views
1

我想從此字符串中提取失敗{"Login":"Failed"}如何設置模式?你也可以提供解釋。我提到this site,但不明白他們設定模式的含義。這就是我想這失敗:使用模式和匹配器

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

首先閱讀您嘗試使用的類的javadoc。 –

回答

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

你不必組您正則表達式,集團在括號中的表達式。這個任務也可以用replace來解決

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

你的字符串是JSON格式。 RegExp的另一種選擇是將其解析爲JSON,然後從JsonObject獲取屬性「Login」。

推薦庫:Google GSON。

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