有没有办法可以从字符串中删除IP?
我们得到的输入文件有时会附加到用户名的IP,例如
Jan vd Merwe Piet Breedt (172.166.23.41) Jan vd Merwe (164.23.23.51) Sarel Fourie (23.12.167.244) Piet Breedt
所以,如果有IP,我想删除它。我一直在寻找很多函数,但似乎无法正确获取索引和参数。
答案 0 :(得分:2)
您可以查找(
并删除剩余的字符串。
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);
}
}
}
打印:
Jan vd Merwe
Piet Breedt
Jan vd Merwe
Sarel Fourie
另一种解决方案,基于正则表达式:
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);
}
}
打印
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)
答案 1 :(得分:1)
使用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("\(.*\)", "");
当然,正则表达式可以专门用于匹配ips,比如
\(\\d{1,3}\.\\d{1,3}\.\\d{1,3}.\\d{1,3}\)
修改强>
以下是如何替换文件中的行(伪代码):