Ahmet Tanakol
Ahmet Tanakol

Reputation: 899

Finding a specific substring in a string

I have been trying to parse a multiple lines string and extract a substring from it. I run "ifconfig" command from ruby file and trying to find the name of the first network interface name. The result of "ifconfig" command is like this

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)

I want the extract the first "wlan" from this string which is wlan1. The order is always the same however first wlan might be "wlan0", "wlan1" etc... I can get it like this however I'm wondering is there any better way to do it?

parsing_string = `ifconfig`

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

Upvotes: 0

Views: 49

Answers (1)

radubogdan
radubogdan

Reputation: 2834

What if there is no wlanX interface? Because of :index which could return nil, you'll end up with NoMethodError

I will rather try something like: puts parsing_string[/(wlan\d)/, 1]

Upvotes: 2

Related Questions