group的含义:
1.groupCount:匹配规则中左边小括号的个数((?
除外).
Pattern pattern = Pattern.compile("<p>(.*?)</p>");
,groupCount为1.
Pattern pattern = Pattern.compile("<p>(.*?)(.+?)</p>");
,groupCount为2.
Pattern pattern = Pattern.compile("<p>(.*?)(.+?)(?.)</p>");
,groupCount为2.
2.Matcher.group(int group):获取第i组匹配到的内容.
matcher.group(0);匹配的整个规则字符串.
matcher.group(i);匹配第i组规则字符串.
3.matcher.start(i group)/end():
int start = matcher.start();返回当前匹配到的字符串在原目标字符串中的位置
int end = matcher.end();返回当前匹配的字符串的最后一个字符在原目标字符串中的索引位置
int start = matcher.start(1);第一个分组匹配的内容,也就是John开始的索引位置,0
4.java中使用正则匹配的完整流程:
Pattern pattern = Pattern.compile("<p>(.*?)</p>");
Matcher matcher = pattern.matcher("<p><b>R</b>espect diversity<br><b>C</b>ontribute to a safe environment</p><p><b>C</b>111111<br><b>C</b>ontribute to a safe environment</p><p><b>D</b>222222<br><b>C</b>ontribute to a safe environment</p><p><b>C</b>333333<br><b>C</b>ontribute to a safe environment</p>");
XLog.d("group_count:" + matcher.groupCount());
while (matcher.find()) {
XLog.d("group0:" + matcher.group(0));
XLog.d("group1:" + matcher.group(1));
}
总结:java正则中的组==子表达式
网友评论