java - 正则表达式从字符串数据中获取特定值

标签 java regex

在执行特定的 shell 命令时,我得到如下输出并将其保存在字符串变量中

dat /var/france.log

exit


bluetooth_mac=45h6kuu
franceIP=testMarmiton
build_type=BFD
france_mac=F4:0E:83:35:E8:D1
seloger_mac=F4:0E:83:35:E8:D0
tdVersion=1.2
td_number=45G67j
france_mac=fjdjjjgj
logo_mac=tiuyiiy

logout
Connection to testMarmiton closed.

Disconnected channel and session

从中我也可以获取如下所示的特定详细信息,并将这些值放入Map中。我如何使用 java 执行此操作。

bluetooth_mac=45h6kuu
build_type=BFD
tdVersion=1.2
seloger_mac=F4:0E:83:35:E8:D0
france_mac=fjdjjjgj

Map<String, String> details =new HashMap<String,String>();
details.put(bluetooth_mac, 45h6kuu);
details.put(build_type, BFD)
etc
etc

最佳答案

解决方案1

如果您使用的是 Java 8,您可以使用:

String fileName = "shell.txt";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {

    Map<String, String> result = stream
            .filter(line -> line.matches("\\w+=\\w+"))
            .map(line -> line.split("="))
            .collect(Collectors.toMap(a -> a[0], a -> a[1]));

} catch (IOException e) {
    e.printStackTrace();
}

输出

{franceIP=testMarmiton, bluetooth_mac=45h6kuu, logo_mac=tiuyiiy, td_number=45G67j, france_mac=fjdjjjgj, build_type=BFD}
<小时/>

解决方案2

似乎有多行具有相同的名称,在这种情况下,我想按 Map<String, List<String>> 进行分组:

String fileName = "shell.txt";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {

    Map<String, List<String>> result = stream
            .filter(line -> line.matches("[^=]+=[^=]+")) // filter only the lines which contain one = signe
            .map(line -> line.split("=")) // split with = sign
            .collect(Collectors.groupingBy(e -> e[0], Collectors.mapping(e -> e[1], Collectors.toList())));

    result.forEach((k, v) -> System.out.println(k + " : " + v));
} catch (IOException e) {
    e.printStackTrace();
}

输出

franceIP : [testMarmiton]
bluetooth_mac : [45h6kuu]
logo_mac : [tiuyiiy]
td_number : [45G67j]
seloger_mac : [F4:0E:83:35:E8:D0]
france_mac : [F4:0E:83:35:E8:D1, fjdjjjgj]
tdVersion : [1.2]
build_type : [BFD]

关于java - 正则表达式从字符串数据中获取特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50407274/

相关文章:

java - REST 的 Spring Security

java - 将 java bean 实现为 jsp servlet

java - 什么正则表达式可以匹配相似的字符?

java - Json 和 Array 序列化 - Java Spring Boot

java - 数组 - 输出必须是一年中的月份

java - 如何从一个数组中删除另一个数组中的对象?

java - 需要一个正则表达式来提取两个 "delimiting"字符串之间的字符串

javascript - 正则表达式 - 检查字符串是否只包含一次模式

regex - 如何使用 grep 的正则表达式从文件中提取 base64 文本

php - 匹配 2-20 个字母数字字符的正则表达式,允许在字符串中的任何位置使用单个连字符