review20

Pattern与Matcher类

模式匹配就是检索和指定模式匹配的字符串。java提供了专门用来进行模式匹配的Pattern类和Matcher类,这些类在java.util.regex包中。

模式对象是对正则表达式的封装。

如:

Pattern p;
String regex = "(http://|www)\56?\\w+\56{1}\\w+\56{1}\\p{Alpha}+";
p = Pattern.compile(regex);

模式对象pattern调用matcher(CharSequence input)方法返回一个Matcher对象matcher,成为匹配对象,参数input用于给出matcher要检索的字符串。

Matcher matcher = pattern.matcher(input);

Matcher对象matcher可以使用下列方法寻找字符串input中是否有和模式regex匹配的子序列(regex是创建模式对象pattern时使用的正则表达式)。

public boolean find():寻找input和regex匹配的下一子序列,如果成功该方法返回true,否则返回false.

public boolean matches():matcher调用该方法判断input是否完全和regex匹配。

public boolean lookingAt():matcher调用该方法判断从input的开始位置是否有和regex匹配的子序列。若lookingAt()方法返回true,matcher调用start()方法和end方法可以得到lookingAt()方法找到的匹配模式的子序列在input中的开始位置和结束位置。matcher调用group()方法可以返回lookingAt()方法找到的匹配模式的子序列。

public boolean find(int start):matcher调用该方法判断input从参数start指定位置开始是否有和regex匹配的子序列,参数start为0,该方法和lookingAt()的功能相同。

public String replaceAll(String replacement):matcher调用该方法返回将与regex匹配的字符串被参数replacement替换后的字符串。

扫描二维码关注公众号,回复: 2613703 查看本文章

public String replaceFirst(String replacement):matcher调用该方法可以返回一个字符串,该字符串是通过把input中第1个与模式regex匹配的字符串替换为参数replacement指定的字符串得到的。

上述部分方法的使用情况如下所示:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test10 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Pattern p;
        Matcher m;
        String regex = "(http://|www)\56?\\w+\56{1}\\w+\56{1}\\p{Alpha}+";
        p = Pattern.compile(regex);
        String s = "新浪:www.sina.cn,央视:http://www.cctv.com,西农:www.nwsuaf.edu.cn,无:www.edu.cn,百度:www.baidu.com";
        System.out.println("原字符串是:" + s);
        m = p.matcher(s);
        while(m.find())
        {
            String str = m.group();
            System.out.println(str);
        }
        System.out.println("剔除字符串中的网站网址后得到的字符串:");
        String result = m.replaceAll("");
        System.out.println(result);
        
    }

}

运行结果如下所示:

猜你喜欢

转载自www.cnblogs.com/liaoxiaolao/p/9440950.html
今日推荐