首页 新闻 论坛 群组 Blog 文档 下载 读书 Tag 网摘 搜索 开源 FAQ 第二书店 博文视点 程序员
频道: 研发 数据库 中间件 信息化 视频 .NET Java 游戏 移动 服务: 人才 外包 培训
    图书品种:235680
       
热门搜索: ASP.NET Ajax Spring Hibernate Java

13.2  测试示例

本节定义一个可重用的测试示例RegexTestHarness.java,用于讲解这个API支持的正则表达式结构。运行这段代码的命令是java RegexTestHarness;不接受命令行参数。这个应用程序重复地循环,提示用户输入正则表达式和输入字符串。使用这个测试示例是可选的,但是你会发现使用它分析后面章节讨论的测试案例是很方便的。

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

      }

    }

  }

}

在继续下一小节之前,请首先保存和编译这段代码,以便确保开发环境支持所需的包。

查看所有评论(0)条】

最近评论



正在载入评论列表...
热点评论