1.正则表达式的几个特殊的方法:
(1) boolean matches(String regex):判断该字符串是否匹配指定的正则表达式(regex)
(2) String replaceAll(String regex,String replacement):用replacement替换字符串中所有匹配指定正则表达式regex的字符
(3) String replaceFirst(String regex,String replacement):用replacement替换字符串中第一个匹配指定正则表达式regex的字符
(4) String[] split(String regex):根据指定正则表达式拆分该字符串后得到的字符串数组
2.正则表达式支持的数量标识符有如下几种模式:
(1)Greedy(贪婪模式):贪婪模式是一直匹配下去,直到无法匹配
(2)Reluctant(勉强模式):用问号(?)表示,它只匹配最少的字符
import java.util.Calendar;
public class TestRegular
{
public static void main(String[] args)
{
String str="hello world";
//贪婪模式
System.out.println(str.replaceFirst("\\w*","."));
//勉强模式
System.out.println(str.replaceFirst("\\w*?","."));
//占用模式
System.out.println(str.replaceFirst("\\w*+","."));
}
}
3.Pattern对象是正则表达式编译后在内存中的表示形式,因此,正则表达式必须先被译成Pattern对象,然后再利用Pattern对象创建对应的Matcher对象。而执行匹配所涉及的状态保留在Matcher对象中
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FindGroup
{
public static void main(String[] args)
{
//Pattern提供一个正则表达式,而matcher提供字符串
Matcher m=Pattern.compile("\\w+").matcher("java is very easy!");
//从字符串中找到与正则表达式匹配的字符串
while(m.find()){
//输出上一次找到的字符串
System.out.println(m.group());
}
int i=0;
//从i处开始扫描字符串,查找匹配字符串
while(m.find(i)){
System.out.println(m.group()+"\t");
i++;
}
}
}