0

I am trying to pass regular expression to process a file line by line. The regular expression works fine if I hard code it in the code, like this.

File.foreach(filename).with_index do |line, line_num|
  md5 = line.scan(/[0-9a-f]{32}/i)
  puts md5
end

This works wonderful and I can see every line that has a MD5 hash on it printed. Now, the problem comes when I try to pass the regular expression to match md5 hashes as a script argument like:

ruby md5.rb -h "/[0-9a-f]{32}/i"

options = {}
OptionParser.new do |opts|
  opts.on('-h', '--hash "<hash regex>"', 'Hash Regex') { |v| options[:hash] = v }
end.parse!

hash = options[:hash]
File.foreach(filename).with_index do |line, line_num|
  md5 = line.scan(hash)
  puts md5
end

1 Answer 1

1

You can pass the inside bits of the regex as a string, then convert it to a regex later eg:

ruby md5.rb -h "[0-9a-f]{32}"

To convert a string into a regex, just use interpolation:

regex = /#{regex_string}/i
Sign up to request clarification or add additional context in comments.

1 Comment

Instead of interpolation, you could also use Regexp.new(regex_string) which will throw a RegexpError if the expression is invalid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.