PHP中的PHP的`preg_match_all`功能

时间:2010-10-01 18:38:23

标签: java php regex preg-match

在PHP中,如果我们需要匹配["one","two","three"]之类的内容,我们可以将以下正则表达式与preg_match一起使用。

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

通过使用括号,我们还可以提取单词一,二和三。我知道Java中的Matcher对象,但无法获得类似的功能;我只能提取整个字符串。我将如何模仿Java中的preg_match行为。

3 个答案:

答案 0 :(得分: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


资源:

答案 1 :(得分:1)

Java Pcre是一个提供所有php pcre功能的Java实现的项目。你可以从那里得到一些想法。检查项目https://github.com/raimonbosch/java.pcre

答案 2 :(得分: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