Pattern Matcher group 简单例子正则表达式
多次使用了Matcher匹配后的group提取需要的内容。记录一下非常简单的demo。 至于正则表达式请参考其他资料,本代码片段使用了d匹配数字 (d+)表示匹配一个或多个数字。 https://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#groupCount() Any non-negative integer smaller than or equal to the value returned by this method is guaranteed to be a valid group index for this matcher. import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AbsMain {
/** * @param args */
final static public String CREATED_DESC = "Created for Step '%s' of project '%s'";
final static public String MATCHER_PATTERN = "Created for Step '(d+)' of project '(d+)'";
public static void main(String[] args) throws IOException {
String str0 = String.format(CREATED_DESC,3,5);
String str1 = String.format(CREATED_DESC,5,78);
String str2 = String.format(CREATED_DESC,6,718);
String str3 = String.format(CREATED_DESC,31,6);
String str4 = String.format(CREATED_DESC,69);
String str5 = String.format(CREATED_DESC,391,62);
String str6 = String.format(CREATED_DESC,367,3);
String str7 = String.format(CREATED_DESC,361,50);
String str8 = String.format(CREATED_DESC,320,503);
String str9 = String.format(CREATED_DESC,36716,37890);
Pattern pattern = Pattern.compile(MATCHER_PATTERN);
Matcher matcher = null;
String[] strArray = {str0,str1,str2,str3,str4,str5,str6,str7,str8,str9};
int matchCount = 0;
int totalCount = strArray.length;
for (String str : strArray) {
System.out.println("Current str:" + str);
matcher = pattern.matcher(str);
if (matcher.matches()) {
matchCount++;
int groupCount = matcher.groupCount();
for (int i = 0 ;i < groupCount + 1; i++) {
System.out.println("TotalGroup:" + groupCount +",Group:" + i+ ",Value:"+ matcher.group(i));
}
}
else {
System.out.println("can't match with pattern.");
}
System.out.println("----------------------------");
System.out.println("");
}
System.out.println("Total StringArray count:" + totalCount + ",matched pattern count:" + matchCount);
}//main
}//class
运行结果: TotalGroup:2,Group:2,Value:5Current str:Created for Step ‘5’ of project ‘78’ TotalGroup:2,Value:78Current str:Created for Step ‘6’ of project ‘718’ TotalGroup:2,Value:718Current str:Created for Step ‘31’ of project ‘6’ TotalGroup:2,Value:6Current str:Created for Step ‘31’ of project ‘69’ TotalGroup:2,Value:69。。。 Total StringArray count:10 matched pattern count:10 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |