Alex. b Alex. b - 4 months ago 10
Ruby Question

Extract env variables from file using regex

# code

ENV['VAR_1'] = 'HELLO 1'
ENV['VAR_2'] = 'HELLO 2'
ENV['VAR_3'] = 'HELLO 3'

# code


How do I extract using ruby and regex each variable and it's value?

Currently I'm doing line by line which is stupid.

S3_SECRET = line.split(' = ').last.delete("'") if line =~ /ENV\['S3_SECRET'\]/
S3_KEY = line.split(' = ').last.delete("'") if line =~ /ENV\['S3_KEY'\]/
S3_BUCKET = line.split(' = ').last.delete("'") if line =~ /ENV\['S3_BUCKET'\]/

Answer

You may have quite a verbose regex like

/^ENV\['(.*?)'\] *= *'(.*?)'$/

See the regex demo.

Details:

  • ^ - start of line
  • ENV\[' - a literal ENV[' substring
  • (.*?) - Group 1 capturing 0+ chars other than a newline as few as possible up to the first
  • '\] - literal '] text
  • *= * - a = sign enclosed with optional (0 or more) spaces
  • ' - a single quote
  • (.*?) - Group 2 capturing 0+ chars other than a newline as few as possible up to the
  • ' - final ' at...
  • $ - the end of the line.

Here is a Ruby demo:

s = <<DATA
# code

ENV['VAR_1'] = 'HELLO 1'
ENV['VAR_2'] = 'HELLO 2'
ENV['VAR_3'] = 'HELLO 3'

# code
DATA
puts s.scan(/^ENV\['(.*?)'\] *= *'(.*?)'$/).to_h

Output: {"VAR_1"=>"HELLO 1", "VAR_2"=>"HELLO 2", "VAR_3"=>"HELLO 3"}