Test Harness
本部分定义了一个可重用的测试工具RegexTestHarness.java,用于探索该 API 支持的正则表达式构造。运行此代码的命令是java RegexTestHarness
;不接受任何命令行参数。该应用程序反复循环,提示用户 Importing 正则表达式和 Importing 字符串。使用此测试工具是可选的,但是您可能会发现它很方便探索下一页中讨论的测试用例。
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");
}
}
}
}
在 continue 下一节之前,请保存并编译此代码,以确保您的开发环境支持所需的程序包。