如何使用流将known_hosts行分成四个部分

时间:2019-04-30 11:39:13

标签: regex java-8 stream

我正在使用Java 8流读取“ known_hosts”文件。 这是常见行的示例:

my_host,0.0.0.0 ssh-rsa xxxxxxxx

对于每一行,我想将其分为4部分:(主机,ip,key_type,key)

但是,我试图在Java中寻找一个正则表达式,但我真的不知道它是如何工作的。

我该如何解决这个问题?

String knownHostsPath = "target/test/known_hosts";
    try (Stream<String> stream = Files.lines(Paths.get(knownHostsPath))) {
        stream.forEach(line -> {
            line.split("*");
        }
        );  

1 个答案:

答案 0 :(得分:1)

您需要使用此正则表达式[, ]来分割行,因为行中的值由逗号或空格分隔。尝试使用修改过的Java代码,

String knownHostsPath = "target/test/known_hosts";

try (Stream<String> stream = Files.lines(Paths.get(knownHostsPath))) {
    List<String[]> list = stream
            .map(x -> x.split("[, ]")) // use map to split each line into array of strings using [, ] regex which means either space or comma
            .filter(x -> x.length == 4) // use filter to retain only values which have four values after splitting to get rid away of junk lines
            .collect(Collectors.toList()); // collect the string array containing your four (host, ip, keytype, key) values as list

    list.forEach(x -> { // print the values or do whatever
        System.out.println(String.format("Host: %s, IP: %s, KeyType: %s, Key: %s", x[0], x[1], x[2], x[3]));
    });
}

打印以下内容,

Host: my_host, IP: 0.0.0.0, KeyType: ssh-rsa, Key: xxxxxxxx
Host: my_host1, IP: 1.2.3.4, KeyType: ssh-rsa1, Key: yyyyyyyy

假设您的文件内容是这个

my_host,0.0.0.0 ssh-rsa xxxxxxxx
my_host1,1.2.3.4 ssh-rsa1 yyyyyyyy