我一直在尝试解析多行字符串并从中提取子字符串。我跑" ifconfig"从ruby文件命令并尝试查找第一个网络接口名称的名称。 " ifconfig"的结果命令就像这样
eth0 Link encap:Ethernet HWaddr *****
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:5439 errors:0 dropped:0 overruns:0 frame:0
TX packets:5439 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:480911 (469.6 KiB) TX bytes:480911 (469.6 KiB)
wlan1 Link encap:Ethernet HWaddr *****
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
wlan5 Link encap:Ethernet HWaddr *****
inet addr:***** Bcast:***** Mask:******
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:30423 errors:0 dropped:5903 overruns:0 frame:0
TX packets:14879 errors:0 dropped:1 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:4968104 (4.7 MiB) TX bytes:1465216 (1.3 MiB)
我希望摘录第一个" wlan"从这个字符串是wlan1。顺序总是相同但是第一个wlan可能是" wlan0"," wlan1"等......我可以这样得到它然而我想知道有没有更好的方法呢?
parsing_string = `ifconfig`
position= parsing_string.index('wlan')
puts parsing_string[position..position+4]
答案 0 :(得分:2)
如果没有wlanX
界面怎么办?由于:index
可以返回nil
,您最终会得到NoMethodError
我宁愿尝试类似:puts parsing_string[/(wlan\d)/, 1]