user3932936 user3932936 - 2 months ago 6
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 = "ubuntu", version: version)
runner = => "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())

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.


the following should work:

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

see regex demo, or repl demo