码迷,mamicode.com
首页 > 编程语言 > 详细

java 正则

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

标签:style   blog   class   code   java   c   

一。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 正则

标签:style   blog   class   code   java   c   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!