1

I'm trying to learn about how to use the Regex API through Oracle's site.

So in the following code, when ran on my machine, I just get the first output statement of no console and nothing else runs. Could anyone explain what's happening?

Also, why would we use console over scanner for Regex?

import java.io.Console;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


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");
            }
        }
    }
}
user3646508
  • 109
  • 5
  • If you're using Eclipse, this is a duplicate of http://stackoverflow.com/questions/4203646/system-console-returns-null – aioobe Feb 16 '15 at 15:36

1 Answers1

0

I'm guessing you run it from within Eclipse. The Eclipse environment does not provide a console. I suggest you run your program manually from the terminal or use something else such as a BufferedReader.

aioobe
  • 413,195
  • 112
  • 811
  • 826