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?

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Also, if you care about IPv6, which you might sooner than you think, that's not going to work at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.