Jafe Lee

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  49 随笔 :: 0 文章 :: 24 评论 :: 0 Trackbacks
1、Java 1.4之后的版本引进了一个用于处理正则表达式的包 java.util.regex.*; 该包主要包含三个类:
  • Pattern : 用来表示一个经过编译处理后的正则表达式。通俗一点来说,就是用一个类来表示一个正则表达式,这个类是从正则表达式构造得到的。这个类并没有public constructor, 如果想得到一个这个类的一个对象则必须调用该类的public static方法:public static Pattern compile(String regex)或者 public static Pattern compile(String regex,int flags)。这两个方法返回一个Pattern型的对象。
  • Matcher : 解释Pattern并执行匹配、查找工作的类,跟Pattern类一样,这个类也没有定义public constructor,要想获得一个Matcher对象必须调用Pattern类的方法 public Matcher matcher(CharSequence input) 来得到。
  • PatternSyntaxException : 一个unchecked exception。当遇到不符和Java正则表达式的语法的时候程序就会抛出这个异常。
2、一个例子(摘自java.sun.com
package regex;

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

public class RegexTestHarness {
    
public static void main(String [] args) {
        Console console 
= System.console();
        
if (console == null) {
            System.err.println(
"No console.");
            System.exit(
1);
        }
        
while (true) {
            Pattern pattern 
= Pattern.compile(console.readLine("%nEnter your regex: "));
            Matcher matcher 
= pattern.matcher(console.readLine("Enter input string to search: "));
            
boolean found = false;
            
while (matcher.find()) {
                console.format(
"I found the text \"%s\"starting at " +
                        
"index %d and ending at index %d. %n", matcher.group(), matcher.start(), matcher.end());
                found 
= true;
            }
            
if (!found)
                console.format(
"No match found.%n");
        }
    }
}
注:由于这个例子使用了JDK 1.6后才有的方法:System.console(),所以这个例子在eclipse和netbeans都不能正常运行。只有在命令行下才能正确运行。如果想在eclipse和nb下运行,好像可以用System.out/in来代替System.console。
posted on 2007-12-09 19:47 Jafe Lee 阅读(888) 评论(0)  编辑  收藏 所属分类: Java

只有注册用户登录后才能发表评论。


网站导航: