【The Java™ Tutorials】【Regular Ex

2018-03-23  本文已影响0人  Ppian

下面是一个可以运行的工具,用于探索Java中的正则表达式。输入正则表达式和要匹配的文本之后,该工具就会输出匹配结果。建议直接用命令行运行,在Eclipse中,System.console()会返回空值,这好像是Eclipse的一个bug

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");
            }
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读