Pattern和Matcher类

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);
  }

运行结果:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值