首页 > 编程语言 > 详细

java 正则

时间:2014-05-13 11:02:29      阅读:425      评论:0      收藏:0      [点我收藏+]

一。start 和end 方法

下面是一个对单词"cat"出现在输入字符串中出现次数进行计数的例子:

bubuko.com,布布扣
public class RegexMatches{
    private static final String REGEX = "\\bcat\\b";   //边界
    private static final String INPUT = "cat cat cat cattie cat";

    public static void main( String args[] ){
       Pattern p = Pattern.compile(REGEX);
       Matcher m = p.matcher(INPUT); // 获取 matcher 对象
       int count = 0;

       while(m.find()) {
         count++;
         System.out.println("Match number "+count);
         System.out.println("start(): "+m.start());
         System.out.println("end(): "+m.end());
      }
   }
}
bubuko.com,布布扣

结果:

bubuko.com,布布扣
Match number 1
start(): 0
end(): 3
Match number 2
start(): 4
end(): 7
Match number 3
start(): 8
end(): 11
Match number 4
start(): 19
end(): 22
bubuko.com,布布扣

 

二。matches 和lookingAt 方法

matches 和lookingAt 方法都用来尝试匹配一个输入序列模式。它们的不同是matcher要求整个序列都匹配,而lookingAt 不要求。

bubuko.com,布布扣
public class RegexMatches{
    private static final String REGEX = "foo";
    private static final String INPUT = "fooooooooooooooooo";
    private static Pattern pattern;
    private static Matcher matcher;

    public static void main( String args[] ){
       pattern = Pattern.compile(REGEX);
       matcher = pattern.matcher(INPUT);

       System.out.println("Current REGEX is: "+REGEX);
       System.out.println("Current INPUT is: "+INPUT);

       System.out.println("lookingAt(): "+matcher.lookingAt());
       System.out.println("matches(): "+matcher.matches());
   }
}
bubuko.com,布布扣

结果:

Current REGEX is: foo
Current INPUT is: fooooooooooooooooo
lookingAt(): true
matches(): false

 

java 正则,布布扣,bubuko.com

java 正则

原文:http://www.cnblogs.com/yuyutianxia/p/3724587.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!