Pattern和Matcher类是专门进行模式匹配的。
使用步骤。假设有字符串:
String str = "I love you";
我们想知道str从哪个位置开始出现love,从哪个位置结束了字符串love。
1.建立模式对象
使用正则表达式做参数得到一个pattern类的实例。
String regex = "love";
Pattern pattern = Pattern.compole(regex);
类方法compole(String regex)返回一个模式对象
2.得到匹配对象
得到可以检索字符串str的Matcher类的实例。
Matcher matcher = pattern.matcher(str);
参数str用于给出matcher要检索的字符串。
调用fine()方法将检索str若检索到love则返回true,未检索则返回false。当返回true时,matcher.stare()值为2(love出现的位置),matcher.end()返回6(love结束的位置),matcher.group()返回love(返回检索的字符串)。
3.常用方法
public boolean find():检索相应字符串若存在则返回true,再次调用该方法,从上一次检索的子序列结束位置开始检索。当fine()返回true时,可以调用start()和end()得到开始位置和结束位置,还可以调用group()返回本次找到的匹配模式的子字符串。
public boolean matchers():判断匹配模式与要检索的字符串是否完全一致。
public boolean lookingAt():判断要检索的字符串中是否有匹配模式中的字符。
public boolean find(int start):从start位置开始检索。
public String repaveAll(String replacement):与匹配模式对应的字符全部更换为replacement。
public String replaceFirst(String replacement):与匹配模式对应的第一个字符更换为replacement。
小例子:
public static void main(String[] args) {
String wangzhi = "新浪新闻:www.xinlang新闻.com";
Pattern p;
Matcher m;
String regex = "[.a-z]";
p = Pattern.compile(regex);
m = p.matcher(wangzhi);
while(m.find()){
String str = m.group();
System.out.print(str);
}
System.out.printf("\n");
String s = m.replaceAll("");
System.out.println(s);
}
运行结果: