1

我正在尝试在字符串中查找数字。我知道查找数字是由 \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"

使用我的 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());

我收到一个错误异常,指出未找到匹配项。我的正则表达式模式或我试图访问与模式匹配的文本的方式有问题。

4

4 回答 4

6

首先,您应该在调用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());
        }
于 2012-12-12T16:07:29.563 回答
0

如果你真的想找到个位数,你需要这个:

Pattern pattern = Pattern.compile("\\d");
Matcher matcher = pattern.matcher(testline);
while (matcher.find()) {
    System.out.println(matcher.group());
}

如果要查找非浮点数,请将正则表达式更改为"\\d+".

于 2012-12-12T16:09:41.167 回答
0

尝试使用\d*而不是 \d+。看看这篇文章-: 在字符串中查找数字。

于 2012-12-12T16:39:19.513 回答
0

只需添加并使用简单的 ktx:

 fun String.digits() = 
      Pattern.compile("\\d+").matcher(this).run { if (find()) group() else "" }!!
于 2019-03-01T15:00:39.733 回答