2010-10-01 22 views
7

在PHP中,如果我們需要匹配類似["one","two","three"]的東西,我們可以使用以下正則表達式與preg_matchPHP在Java中的'preg_match_all`功能

$pattern = "/\[\"(\w+)\",\"(\w+)\",\"(\w+)\"\]/" 

通過使用括號,我們也能夠提取單詞一,二和三。我知道Java中的Matcher對象,但我無法獲得類似的功能;我只能提取整個字符串。我將如何去模仿Java中的preg_match行爲。

回答

13

使用匹配器,要獲取組必須使用Matcher.group()方法。

例如:

Pattern p = Pattern.compile("\\[\"(\\w+)\",\"(\\w+)\",\"(\\w+)\"\\]"); 
Matcher m = p.matcher("[\"one\",\"two\",\"three\"]"); 
boolean b = m.matches(); 
System.out.println(m.group(1)); //prints one 

記住group(0)是相同的整體匹配序列。

Example on ideone


資源:

0

我知道這篇文章來自2010年,只是爲了尋找它,可能是其他人仍然需要它。所以這裏是我爲我的需要創建的功能。

基本上,它將替換所有關鍵字從JSON值(或模型,或任何數據源)

如何使用:

JsonObject jsonROw = some_json_object; 
String words = "this is an example. please replace these keywords [id], [name], [address] from database"; 
String newWords = preg_match_all_in_bracket(words, jsonRow); 

我在我的共享適配器使用此代碼。

public static String preg_match_all_in_bracket(String logos, JSONObject row) { 
    String startString="\\[", endString="\\]"; 
    return preg_match_all_in_bracket(logos, row, startString, endString); 
} 
public static String preg_match_all_in_bracket(String logos, JSONObject row, String startString, String endString) { 
    String newLogos = logos, withBracket, noBracket, newValue=""; 
    try { 
     Pattern p = Pattern.compile(startString + "(\\w*)" + endString); 
     Matcher m = p.matcher(logos); 
     while(m.find()) { 
      if(m.groupCount() == 1) { 
       noBracket = m.group(1); 
       if(row.has(noBracket)) { 
        newValue = ifEmptyOrNullDefault(row.getString(noBracket), ""); 
       } 
       if(isEmptyOrNull(newValue)) { 
        //no need to replace 
       } else { 
        withBracket = startString + noBracket + endString; 
        newLogos = newLogos.replaceAll(withBracket, newValue); 
       } 
      } 
     } 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    return newLogos; 
} 

我也是Java/Android新手,請隨時糾正,如果你認爲這是一個糟糕的實現或其他東西。 tks