Java正则表达式

group的含义:

1.groupCount:匹配规则中左边小括号的个数((?除外).
Pattern pattern = Pattern.compile("

(.*?)

");,groupCount为1.
Pattern pattern = Pattern.compile("

(.*?)(.+?)

");
,groupCount为2.
Pattern pattern = Pattern.compile("

(.*?)(.+?)(?.)

");
,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("

(.*?)

"); Matcher matcher = pattern.matcher("

Respect diversity
Contribute to a safe environment

C111111
Contribute to a safe environment

D222222
Contribute to a safe environment

C333333
Contribute to a safe environment

"); XLog.d("group_count:" + matcher.groupCount()); while (matcher.find()) { XLog.d("group0:" + matcher.group(0)); XLog.d("group1:" + matcher.group(1)); }

总结:java正则中的组==子表达式

你可能感兴趣的:(Java正则表达式)