我试图在字符串中找到数字.我知道找到一个数字是由\ d完成的,但当我在一个示例文本上尝试时,如下所示:
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"
Run Code Online (Sandbox Code Playgroud)
使用我的java代码
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());
Run Code Online (Sandbox Code Playgroud)
我收到一个错误异常,说明找不到匹配项.我的正则表达式模式或我试图访问匹配模式的文本的方式有问题.
首先,你应该在调用Matcher.group()之前调用Matcher.find()
使用"\\d+",如果你认为127作为一个整体单一的数字为正则表达式.
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(s);
while(m.find()){
System.out.println(m.group() + " " + m.start() + " " + m.end());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7487 次 |
| 最近记录: |