- Pattern:正则表达式的模式类
- 获取对象的函数Pattern pattern=Pattern.compiler(regex);
- 功能函数:
- 1.pattern.split(String targetString);
- Matcher:正则表达式的匹配类
- 获取对象的函数Matcher matcher=pattern.matcher(String targetString);
- 功能函数:
- 匹配功能
- 1.matcher.mathces();
- 2.matcher.reset(String targetString);
- 查找功能
- 1.方式一:
- matcher.find(int statIndex);
- 例子:
- while(matcher.find(0)){
- matcher.start();//匹配的起始Index
- matcher.end()-1;// 匹配的终止Index
- }
- 2.方式二:
- matcher.matches();//全词匹配,类似String.matches(String s);
- 3.方式三:
- matcher.lookingAt();//—只能匹配一次,matcher.find(0);
- 注意:
- matcher.find()会收到lookingAt()的影响
- 1.先执行matcher.lookingAt();//假设匹配
- 2.matcher.find();//只会从第二个地方开始匹配(如果有的话)
- 其他的功能函数
- matcher.start();//匹配的Start Index
- matcher.end();//匹配的End Index
- Matcher.appendReplacement(StringBuffer,”replace”);//把匹配的部分进行替换”replace”其他的部分不变
- Matcher.appendTail(StringBuffer stringBuffer);
- 例子:
Pattern pattern = Pattern.compile("\\d+"); Matcher matcher=pattern.matcher("123yangyun 123 unun123ddd 143 54647 68678 67568");
StringBuffer stringBuffer=new StringBuffer();
while(matcher.find()){
System.out.println(matcher.start()+"---"+matcher.end());
matcher.appendReplacement(stringBuffer,"!!!");
//matcher.appendTail(stringBuffer);
System.out.println(stringBuffer.toString());
}
结果:
0---3
!!!
11---14
!!!yangyun !!!
19---22
!!!yangyun !!! unun!!!
26---29
!!!yangyun !!! unun!!!ddd !!!
30---35
!!!yangyun !!! unun!!!ddd !!! !!!
36---41
!!!yangyun !!! unun!!!ddd !!! !!! !!!
42---47
!!!yangyun !!! unun!!!ddd !!! !!! !!! !!!
- 例子:
Pattern pattern = Pattern.compile("\\d+"); Matcher matcher=pattern.matcher("123yangyun 123 unun123ddd 143 54647 68678 67568");
while(matcher.find()){
StringBuffer stringBuffer=new StringBuffer();
System.out.println(matcher.start()+"---"+matcher.end());
matcher.appendReplacement(stringBuffer,"!!!");
matcher.appendTail(stringBuffer);
System.out.println(stringBuffer.toString());
}
0---3
!!!yangyun 123 unun123ddd 143 54647 68678 67568
11---14
yangyun !!! unun123ddd 143 54647 68678 67568
19---22
unun!!!ddd 143 54647 68678 67568
26---29
ddd !!! 54647 68678 67568
30---35
!!! 68678 67568
36---41
!!! 67568
42---47
!!!
- 4.Group————与模式regex有关
- 有括号才有组
- Pattern pattern=Pattern.compile(Regex);//eg:String regex=new String(“([a-z]+)(\\d+)");
- Matcher matcher=pattern.Matcher(String target);//目标字符串target
- while(matcher.find()){
- System.out.println(matcher.group());//匹配的部分
- System.out.print(matcher.groupCount());//一定是2
- }