【问题标题】:Finding a specific substring in a string在字符串中查找特定子字符串
【发布时间】:2015-05-01 09:02:39
【问题描述】:

我一直在尝试解析多行字符串并从中提取子字符串。我从 ruby​​ 文件运行“ifconfig”命令并​​尝试查找第一个网络接口名称的名称。 “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)

我想从 wlan1 这个字符串中提取第一个“wlan”。顺序总是相同的,但是第一个 wlan 可能是“wlan0”、“wlan1”等......我可以这样得到它但是我想知道有没有更好的方法来做到这一点?

parsing_string = `ifconfig`

position= parsing_string.index('wlan')
puts parsing_string[position..position+4]

【问题讨论】:

    标签: ruby string parsing


    【解决方案1】:

    如果没有wlanX接口怎么办?因为:index 可以返回nil,所以你最终会得到NoMethodError

    我宁愿尝试类似:puts parsing_string[/(wlan\d)/, 1]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 1970-01-01
      • 2015-08-31
      • 2013-04-14
      • 2015-08-06
      • 2011-07-13
      相关资源
      最近更新 更多