gpt4 book ai didi

java - 为什么在我的正则表达式中从错误的区域捕获组? (Java 7)

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:54:07 26 4
gpt4 key购买 nike

正在从错误的区域捕获数据。它从 eth1 而不是 eth0 捕获 IP 地址字段和子网。我不明白为什么会这样。我也尝试了 matcher.find(0) 但得到了相同的结果。

String[] dataNames = new String[]{"eth0Ip", "eth0Subnet"}
dataExtractionPattern = Pattern.compile("eth0 .*inet (?<eth0Ip>\\S+) mask (?<eth0Subnet>\\S+)",Pattern.DOTALL);

Matcher matcher = dataExtractionPattern.matcher(receivedDataString);
if (matcher.find()) {
for (String key : dataNames) {
String dataValue;
dataValue = matcher.group(key);
extractedData.put(key, dataValue);
}
hasData = true;
}

输入字符串是:

lo0     Link type:Local loopback  Queue:none        inet 127.0.0.1  mask 255.255.255.255        UP RUNNING LOOPBACK        MTU:1500  metric:1  VR:0        RX packets:4 mcast:0 errors:0 dropped:1        TX packets:4 mcast:0 errors:0        collisions:0 unsupported proto:0        RX bytes:172  TX bytes:172eth0    Link type:Ethernet  HWaddr 00:25:f2:5e:9c:34  Queue:none        inet 10.1.2.2  mask 10.1.2.1  broadcast 255.255.255.254        RUNNING BROADCAST        MTU:1000  metric:1  VR:0        RX packets:0 mcast:0 errors:0 dropped:0        TX packets:0 mcast:0 errors:0        collisions:0 unsupported proto:0        RX bytes:0  TX bytes:0eth1    Link type:Ethernet  HWaddr 00:25:f2:5e:9c:33  Queue:none        inet 192.168.200.51  mask 255.255.255.0  broadcast 192.168.200.255        UP RUNNING BROADCAST        MTU:1500  metric:1  VR:0        RX packets:0 mcast:0 errors:0 dropped:0        TX packets:0 mcast:0 errors:0        collisions:0 unsupported proto:0        RX bytes:0  TX bytes:0

对于eth0 ip,它错误地捕获了192.168.200.51和掩码255.255.255.0

最佳答案

如 nhahtdh 所述,.*部分是贪婪的,将尽可能多地匹配,意味着直到最后一个字符的所有内容,您的模式的其余部分将跟随。

您可以通过添加 ? 将量词的匹配行为更改为“不贪婪/惰性”在他们之后:

dataExtractionPattern = Pattern.compile("eth0 .*?inet (?<eth0Ip>\\S+)  mask (?<eth0Subnet>\\S+)",Pattern.DOTALL);

这将尽可能少地匹配,以便您找到第一次出现的 inet (?<eth0Ip>\\S+) mask (?<eth0Subnet>\\S+) .

关于java - 为什么在我的正则表达式中从错误的区域捕获组? (Java 7),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14189717/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com