Java Regex查找字符串中的数字

时间:2012-12-12 16:00:42

标签: java regex

我正在尝试在字符串中查找数字。我知道找到一个数字是由\ 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 个答案:

答案 0 :(得分:6)

首先,您应在调用Matcher.find()

之前致电Matcher.group() 如果您将127视为一个整数,请使用"\\d+"作为正则表达式。

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

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

尝试使用 \ d * 而不是\ d +。 看看这篇文章: Finding a Number in a string.

答案 3 :(得分:0)

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

 fun String.digits() = 
      Pattern.compile("\\d+").matcher(this).run { if (find()) group() else "" }!!