Java Regex Finding digits in a String

java, regex

Solution

Firstly, you should call Matcher.find() before you invoke Matcher.group()

use `"\\d+"` as regex if you consider 127 as a whole single digit.

        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher(s);
        while(m.find()){
        System.out.println(m.group() + " " + m.start() + " " + m.end());
        }

Problem

I am trying to find digits in a string. I know that in finding a digit is done by \d but when I try it on a sample text like the following: ``` 127.0.0.1 - - [11/Dec/2012:11:57:36 -0500] "GET http:// localhost/ HTTP/1.1" 503 418 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11" ``` using my java code ``` Pattern test = Pattern.compile("\\d"); testLine = in.readLine(); // basically the text above // extract date and time log in and number of times a user has hit the page numTimesAccess++; // increment number of lines in a count System.out.println(test.matcher(testLine).group()); System.out.println(test.matcher(testLine).start()); System.out.println(test.matcher(testLine).end()); ``` I get an error exception stating that No Match is found. Is something wrong with my regular expression patter or in the way I am trying to access the text matching the patterns.

Original source