illegalStateException when using the java matcher class


I am trying to get a webpage, load it into a string builder, using a BufferedReader and then use a regex to look for and retrieve words or in this case groups of words (department names like computer-science, Electrical-Engineering etc..) that match the regex pattern. I am using the Pattern and Matcher class that java provides but am running into an illegalStateException. I have been staring at this code for quite a while and would like some fresh perspective on what the problem might be. I know it has something to do with the m.find() and methods. Any help would be greatly appreciated.

I would say from the output I am getting, it recognizes the first words that matches the regex and start throwing illegalStateException after that.

I have also posted my code below:

public class Parser{

    static StringBuilder theWebPage;
    ArrayList<String> courseNames;
    //ArrayList<parserObject> courseObjects;

    public static void main(String[] args)
        Parser p = new Parser();

        theWebPage = new StringBuilder();
        try {
                URL theUrl = new URL("");
                BufferedReader reader = new BufferedReader(new InputStreamReader(theUrl.openStream()));
                String str = null;

                while((str = reader.readLine())!=null)
                    theWebPage.append(" ").append(str);

            } catch (MalformedURLException e) {

            } catch (IOException e) {


    public Parser()
        //parserObject courseObject = new parserObject();
        //courseObjects = new ArrayList<parserObject>();
        courseNames = new ArrayList<String>();
        //theWebPage=" ";

    public void matchString()
        String matchRegex = "#\\w+(-\\w+)+";
        Pattern p = Pattern.compile(matchRegex);
        Matcher m = p.matcher(theWebPage);
        int i=0;
        int x=0;

                System.out.println("inside matches method " + i);

                     x = m.end();
                    PrintStream out = new PrintStream(new FileOutputStream("/Users/xxxx/Desktop/output.txt"));


                }catch(IllegalStateException e)
                } catch (FileNotFoundException e) {
                    System.out.println("FileNotFound Exception");

The problem is that you call:

x = m.end();

even though you may not have a match. Why not incorporate your call to find() into your while statement, thereby making it a guard statement also:

while (m.find()) {