String extraction is one of the main tasks that all programmers need. It's often difficult because we don't get an easy string presentation from which to extract useful data/information. Here are some helpful Ruby string-extraction cases.
Extracting Network Strings
Extracting MAC address from string
We need to extract all MAC addresses from an arbitrary string
mac ="ads fs:ad fa:fs:fe: Wind00-0C-29-38-1D-61ows 1100:50:7F:E6:96:20dsfsad fas fa1 3c:77:e6:68:66:e9 f2"
Using Regular Expressions
This regular expression should support Windows and Linux MAC address formats.
Assume we have the following HTML contents and we need to get strings only and eliminate all HTML tags
string ="<!DOCTYPE html><html><head><title>Page Title</title></head><body><h1>This is a Heading</h1><p>This is another <strong>contents</strong>.</p></body></html>"puts string.gsub(/<.*?>/,'').strip
Returns
Page Title
This is a Heading
This is another contents.
Parsing colon separated data from a file
During a pentest, you may need to parse text that has a very common format as follows
description : AAAA
info : BBBB
info : CCCC
info : DDDD
solution : EEEE
solution : FFFF
reference : GGGG
reference : HHHH
see_also : IIII
see_also : JJJJ
The main idea is to remove repeated keys and pass to one key with an array of values.
#!/usr/bin/env ruby## KING SABRI | @KINGSABRI# Usage:# ruby noawk.rb file.txt#file =File.read(ARGV[0]).split("\n")defparser(file) hash = {} # Datastore splitter = file.map { |line| line.split(':',2) } splitter.each do|k, v| k.strip! # remove leading and trailing whitespaces v.strip! # remove leading and trailing whitespacesif hash[k] # if this key exists hash[k] << v # add this value to the key's arrayelse# if not hash[k] = [v] # create the new key and add an array contains this valueendend hash # return the hashendparser(file).each {|k, v|puts"#{k}:\t#{v.join(', ')}"}