使用Regex Java从文件中获取所有IP地址

时间:2013-02-14 01:54:06

标签: java regex

我正在尝试读取文本文件,搜索所有有效的IP地址并打印它们。使用Scanner类读取文件,文件的全部内容存储在字符串中;然后我使用Java的util.regex Pattern和Matcher搜索所有有效的IP地址并逐个打印。这是我到目前为止编写的代码:

    String inp ="";
    File file = new File("C:\\input.txt");
    try {
        Scanner scan = new Scanner(file);
        while(scan.hasNextLine()) {
            inp += scan.nextLine() + " ";
        }
    } catch (FileNotFoundException f) {
        f.printStackTrace();
    }

    System.out.println("File inp string is "+inp);
    Pattern pattern = 
        Pattern.compile("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)");
    Matcher match = pattern.matcher(inp);
    while(match.find()) {
        System.out.println("IP found: "+match.group());
    }

该文件的内容如下:

127.0.0.1 1:00 AM
User entered host
255.1.2.2 11:00 PM
127.0.0.1 1:00 AM

我得到的输出是:

File inp string is 127.0.0.1 1:00 AM User entered host 255.1.2.2 11:00 PM 127.0.0.1 1:00 AM 
IP found: 127.0.0.1

这是我从输入字符串中获得的唯一IP。我不明白为什么模式匹配器会忽略其他3个IP。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

从正则表达式的开头删除^,或者在从文件中读取的每一行之后添加新的行标记\n

也不要使用+=运算符连接文件的行,因为每次执行时都会创建新的String。而是使用StringBuilder#append(yourLine)