Reputation: 261
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.
Upvotes: 2
Views: 11687
Reputation: 2496
just add and use the simple ktx:
fun String.digits() =
Pattern.compile("\\d+").matcher(this).run { if (find()) group() else "" }!!
Upvotes: 0
Reputation: 367
Try using \d* instead of \d+. Have a look at this post-: Finding a Number in a string.
Upvotes: 0
Reputation: 46408
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());
}
Upvotes: 7
Reputation: 37813
If you really want to find single digits, you need this:
Pattern pattern = Pattern.compile("\\d");
Matcher matcher = pattern.matcher(testline);
while (matcher.find()) {
System.out.println(matcher.group());
}
if you want to find non-floating-point numbers, change the regex to "\\d+"
.
Upvotes: 0