我有一个看起来像下面的列表:
[
StartingNmap7.60(https: //nmap.org)at2020-02-1713: 32IST,
Nmapscanreportfor192.168.1.1(192.168.1.1),
Hostisup(0.0012slatency).,
Nmapscanreportforbevywise_37e0(192.168.1.4),
Hostisup(0.14slatency).,
Nmapscanreportforshiv-thinkpad-t420(192.168.1.5),
Hostisup(0.0072slatency).,
Nmapscanreportforvivo-1726(192.168.1.12),
Hostisup(0.028slatency).,
Nmapscanreportforrealme-5(192.168.1.13),
Hostisup(0.13slatency).,
Nmapdone: 256IPaddresses(5hostsup)scannedin21.02seconds
]
看起来很乱。我想从该列表中获取一些数据。我希望所需的输出如下所示:
[{"host name":"192.168.1.1","IP address":192.168.1.1"},
{"host name":"bevywise_37e0","IP address:"192.168.1.4"},
{"host name":"shiv-thinkpad-t420","IP address":"192.168.1.5"},
{"host name":"vivo-1726","IP address":"192.168.1.12"},
{"host name":"realme-5","IP address":"192.168.1.13"}]
由于我是java的新手,所以我不知道该怎么做。为我提供一些解决方案。
答案 0 :(得分:1)
如果此列表是字符串列表/字符串数组,则可以进行以下操作
按字符串前缀过滤列表,在您的情况下为
String prefix = "Nmapscanreportfor";
创建格式模板,将解析的数据放在其中
字符串模板=“ {\”主机名\“:\”%s \“,\” IP地址\“:%s \”}“;
然后遍历您的列表并解析主机名和IP地址。 String.indexOf()将很有用。例如。要获取主机名,您可以
listEntry.substring(prefix.length(), entry.indexOf("("))
对于ip来说,将是相似的,只需找到第一个“(”和最后一个“)”即可。之间的字符串是您的IP地址。
当拥有主机名和IP地址时,可以使用String.format()方法填充模板字符串占位符。
要遍历列表,可以将其用于循环或流。有了流,它将看起来非常漂亮
List<String> newList = Arrays.stream(array) //if it's array of list.stream() if it's list
.filter(entry -> entry.startsWith(prefix))
.map(entry -> String.format(template, %your hostname%, %your ip address%))
.collect(Collectors.toList());