packagecom.zwj.string;importjava.util.regex.MatchResult;importjava.util.regex.Matcher;importjava.util.regex.Pattern;public classMatcherDemo {public static voidmain(String[] args) {//userStringRegular();//userMatcherRegular();
userMatcherResultRegular();
}
public static voiduserStringRegular() {
String str1= "1 2 3 4 54 5 6";
String[] numbers= str1.split(" +");for(String temp : numbers) {
System.out.println(temp);
}//替换,替换所有的数字为* abd***:adad*****:asdadasadsfgi#%^^****
String str2 = "abd123:adad46587:asdadasadsfgi#%^^9090";
System.out.println(str2.replaceAll("[0-9]", "*"));
System.out.println(str2.replaceAll("\\d", "*"));//匹配匹配邮箱
String mail1 = "[email protected]";
String mail2= "[email protected]";
String mail3= "[email protected]";//String mainRegex =//"[0-9a-zA-Z_]+@[0-9a-zA-Z_]++(\\.[0-9a-zA-Z_]+{2,4})+";
String mainRegex = "\\w+@\\w+(\\.\\w{2,4})+";
System.out.println(mail1.matches(mainRegex));//true
System.out.println(mail2.matches(mainRegex));//true
System.out.println(mail3.matches(mainRegex));//false
}
public static voiduserMatcherRegular() {//匹配出3个字符的字符串
String str = "abc 124 ewqeq qeqe qeqe qeqe aaaa fs fsdfs d sf sf sf sf sfada dss dee ad a f s f sa a'lfsd;'l";
Pattern pt= Pattern.compile("\\b\\w{3}\\b");
Matcher match=pt.matcher(str);while(match.find()) {
System.out.println(match.group());
}//匹配出邮箱地址
String str2 = "dadaadad da da dasK[PWEOO-123- [email protected] [email protected] =0KFPOS9IR23J0IS [email protected]@ADA.COM.CN [email protected] UFSFJSFI-SI- ";
Pattern pet2= Pattern.compile("\\b\\w+@\\w+(\\.\\w{2,4})+\\b");
Matcher match2=pet2.matcher(str2);while(match2.find()) {
System.out.println(match2.group());
}//匹配
String sr = "dada ada adad adsda ad asdda adr3 fas daf fas fdsf 234 adda";//包含两个匹配组,一个是三个字符,一个是匹配四个字符
Pattern pet = Pattern.compile("\\b(\\w{3}) *(\\w{4})\\b");
Matcher match1=pet.matcher(sr);int countAll = match1.groupCount();//2
while(match1.find()) {
System.out.print("匹配组结果:");for (int i = 0; i < countAll; i++) {
System.out.print(String.format("\n\t第%s组的结果是:%s", i + 1,
match1.group(i+ 1)));
}
System.out.print("\n匹配的整个结果:");
System.out.println(match1.group());
}}public static voiduserMatcherResultRegular() {
String sr= "dada ada adad adsda ad asdda adr3 fas daf fas fdsf 234 adda";
Pattern pet= Pattern.compile("\\b(\\w{3}) *(\\w{4})\\b");
Matcher match=pet.matcher(sr);
MatchResult ms= null;while(match.find()) {
ms=match.toMatchResult();
System.out.print("匹配对象的组结果:");for (int i = 0; i < ms.groupCount(); i++) {
System.out.print(String.format("\n\t第%s组的结果是:%s", i + 1,
ms.group(i+ 1)));
}
System.out.println(ms.group());
}
}}