本节定义一个可重用的测试示例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");
}
}
}
}
在继续下一小节之前,请首先保存和编译这段代码,以便确保开发环境支持所需的包。