PHP中的PHP的`preg_match_all`function
在PHP中,如果我们需要匹配类似["one","two","three"]
,我们可以使用以下正则表达式和preg_match
。
$pattern = "/\[\"(\w+)\",\"(\w+)\",\"(\w+)\"\]/"
通过使用括号,我们还能够提取单词一,二和三。 我知道Java中的Matcher
对象,但是我无法获得类似的function; 我只能提取整个字符串。 我将如何模仿Java中的preg_match
行为。
使用Matcher,要获取组,您必须使用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)
是相同的整个匹配序列。
关于ideone的示例
资源:
- Javadoc – Matcher.group()
Java Pcre是一个提供所有php pcre函数的Java实现的项目。 你可以从那里得到一些想法。 检查项目https://github.com/raimonbosch/java.pcre
我知道这篇文章来自2010年,因为我刚刚搜索过它,可能是其他人仍然需要它。 所以这是我为我的需要创建的function。
基本上,它将使用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