Reputation: 37
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
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):
Upvotes: 1
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