user3932936 user3932936 - 3 months ago 13
Ruby Question

Changing syntax with regex

I am having some trouble with ruby syntax in chef (the configuration management tool).

The difference I am dealing with is assigning attributes such as below:

runner = ChefSpec::Runner.new(platform: "ubuntu", version: version)
runner = ChefSpec::Runner.new(:platform => "ubuntu", :version => version)


I need to be able to switch between these two syntax's as they seem to work in different versions of chef/ruby - we will be upgrading but for now need a fix.

I'm novice with regexp, but have been trying like this in python:

for line in fileinput.input(inplace=1, backup='.bak'):
line = re.sub('(\w\w...): ',':"\1" =>', line.rstrip())
print(line)


I don't know what the attribute name will be, or what precedes it, only that a single
:
follows a word (of 2 or more characterss). I'm happy assuming that there will always be a space after the
:
but I seem to be having trouble "picking up" the attribute name to replace and re-use later.

Answer

the following should work:

for line in fileinput.input(inplace=1, backup='.bak'):
  line = re.sub('(\w+): ', ':\g<1> => ', line.rstrip())
  print(line)

see regex demo, or repl demo

Comments