0

I'm trying to read a text file, search for all valid IP addresses and print them. The file is read using the Scanner class and the entire contents of the file are stored in a string; then I use Java's util.regex Pattern and Matcher to search for all valid IP addresses and print them one by one. This is the code I've written so far:

    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());
    }

The contents of the file are the following:

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

The output I get is:

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

That's the only IP I get from the input string. I don't understand why the other 3 IP's are ignored by the pattern matcher. Can anyone help?

4

1 に答える 1

2

^正規表現の先頭から削除するか\n、ファイルから読み取る各行の後に新しい行マークを追加します。

+=また、実行するたびに新しい文字列が作成されるため、ファイルの行を演算子で連結しないでください。代わりに を使用しますStringBuilder#append(yourLine)

于 2013-02-14T01:59:44.217 に答える