Jaques
Jaques

Reputation: 37

Remove IP addresses from a String in Java

Is there any way that you can remove IPs from a string?

The input file we get sometimes has IPs attached to the user name, e.g.

Jan vd Merwe
Piet Breedt (172.166.23.41)
Jan vd Merwe (164.23.23.51)
Sarel Fourie (23.12.167.244)
Piet Breedt

So if there is an IP, I want to remove it. I have been looking at alot of functions but cant seem to get the indexing and parameters right.

Upvotes: 0

Views: 1822

Answers (2)

helpermethod
helpermethod

Reputation: 62165

Use String.replace():

String myString = "Piet Breedt (172.166.23.41)";
// replace everything in between the parens (including the parens) by the empty String
myString = myString.replace("\(.*\)", "");

Of course, the regex could be specialised to only match ips, something like

\(\\d{1,3}\.\\d{1,3}\.\\d{1,3}.\\d{1,3}\)

EDIT

Here's how you would replace the lines in the files (pseudocode):

  1. Open the original file. Open a temporary file.
  2. Read line by line. This will give you a String for every line.
  3. Remove the contents within the String. Write the new String to the temporary file.
  4. When done, replace the original file by the temporary file.

Upvotes: 1

aioobe
aioobe

Reputation: 420991

You could look for the ( and remove the remaining string.

public class Main {

    public static void main(String[] args) {

        String[] names = { "Jan vd Merwe", 
                           "Piet Breedt (172.166.23.41)",
                           "Jan vd Merwe (164.23.23.51)", 
                           "Sarel Fourie (23.12.167.244)" };

        for (String name : names) {

            int parIndex = name.indexLastOf('(');
            if (parIndex != -1)
                name = name.substring(0, parIndex-1);

            System.out.println(name);
        }
    }
}

prints:

Jan vd Merwe
Piet Breedt
Jan vd Merwe
Sarel Fourie

Another solution, based on regular expressions:

    String[] names = { "Jan vd Merwe", 
                       "Piet Breedt (172.166.23.41)",
                       "Jan vd Merwe (164.23.23.51)", 
                       "Sarel Fourie (23.12.167.244)" };

    String ipExp = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
    Pattern pattern = Pattern.compile("(.*?)\\s*(\\(" + ipExp + "\\))?");

    for (String nameIp : names) {
        Matcher m = pattern.matcher(nameIp);
        if (m.matches()) {
            String name = m.group(1);
            String ip = m.group(2) == null ? "n/a" : m.group(2);
            System.out.printf("Name: %s, Ip: %s%n", name, ip);
        }
    }

Prints

Name: Jan vd Merwe, Ip: n/a
Name: Piet Breedt, Ip: (172.166.23.41)
Name: Jan vd Merwe, Ip: (164.23.23.51)
Name: Sarel Fourie, Ip: (23.12.167.244)

Upvotes: 2

Related Questions