codewarrior
codewarrior

Reputation: 1034

get all ip addresses from a file using Regex Java

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?

Upvotes: 0

Views: 4134

Answers (1)

Pshemo
Pshemo

Reputation: 124215

Remove ^ from beginning of your regex, or add new line mark \n after each line you read from your file.

Also don't concatenate lines of your file with += operator because it creates new String every time you do it. Instead use StringBuilder#append(yourLine).

Upvotes: 2

Related Questions