import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
/*
* Pattern类: 可理解成正则表达式的工具
* Matcher类: 可理解成正则匹配结果(包括对结果的处理功能)
*/
public class RegExpDemo2 {
@Test //判断结果中是否存在对应正则表达式中匹配的子串---注意,String中matches()方法是完整匹配,这里是是否存在子串
public void demo1(){
String str="010-1234567822";
Pattern p = Pattern.compile("0\\d{2}-\\d{8}");
Matcher m = p.matcher(str); //str是被匹配对象
boolean boo = m.find();
System.out.println(boo);//true
}
@Test //到被匹配字符串中查找指定模式的内容
public void demo2(){
String str = "010-12345567890aas021-6543217811111";
Pattern p = Pattern.compile("0\\d{2}-\\d{8}",Pattern.MULTILINE);//跨行匹配
Matcher m = p.matcher(str);
m.find();
String res = m.group();
System.out.println(res); //010-12345567
m.find();//从当前位置开始往后找
String res2 = m.group();
System.out.println(res2); //021-65432178
m.find(0); //让游标从指定位置开始找,这里为从0位置开始
String res3 = m.group();
System.out.println(res3); //010-12345567
}
@Test //到被匹配字符串中 遍历出 所有匹配的子串
public void demo3(){
String str = "b010-1234556789010-1112aasw021-65432178111a010-6666888801";
Pattern p = Pattern.compile("[a,b,u]0\\d{2}-\\d{8}",Pattern.CASE_INSENSITIVE);//大小写不敏感
Matcher m = p.matcher(str);
while(m.find()){
String res = m.group();
System.out.println(res);
}
}
}
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
/*
* Pattern类: 可理解成正则表达式的工具
* Matcher类: 可理解成正则匹配结果(包括对结果的处理功能)
*/
public class regexDemo2 {
@Test
public void demo1(){
String str="010-1234567822";
Pattern p=Pattern.compile("0\\d{2}-\\d{8}");
Matcher m=p.matcher(str);//str是被匹配对象
boolean boo = m.find();
System.out.println(boo);//true
}
@Test
public void demo2(){
String str = "010-12345567890aas021-6543217811111";
Pattern p=Pattern.compile("0\\d{2}-\\d{8}", Pattern.MULTILINE);//跨行匹配
Matcher m=p.matcher(str);
m.find();
String res=m.group();
System.out.println(res); //010-12345567
m.find();
String res2 = m.group();
System.out.println(res2); //021-65432178
m.find(0);//让游标从指定位置开始找,这里为从0位置开始
String res3 = m.group();
System.out.println(res3); //010-12345567
}
@Test
public void demo3(){
String str = "b010-1234556789010-1112aasw021-65432178111a010-6666888801";
Pattern p = Pattern.compile("[a,b,u]0\\d{2}-\\d{8}",Pattern.CASE_INSENSITIVE);//大小写不敏感
Matcher m = p.matcher(str);
while(m.find()){
String res = m.group();
System.out.println(res);
}
}
}