美文网首页
【The Java™ Tutorials】【Regular Ex

【The Java™ Tutorials】【Regular Ex

作者: Ppian | 来源:发表于2018-03-23 16:20 被阅读0次

    下面是一个可以运行的工具,用于探索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");
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:【The Java™ Tutorials】【Regular Ex

          本文链接:https://www.haomeiwen.com/subject/lyswvxtx.html