meallhour meallhour - 11 months ago 143
Ruby Question

Getting substring value in Chef ruby

I have a string that has the following value:


I am trying to fetch only
from the string. I am using the following code but it doesn't seem to work

substring = ucp-1.1.0_dtr-2.0.0.gsub('ucp-','')


String's [] and a simple regex will do it:

'ucp-1.1.0_dtr-2.0.0'[/[\d.]+/] # => "1.1.0"

This works because the search will stop as soon as it matches, so the first occurrence wins resulting in 1.1.0.

If you wanted the second/last occurrence then adding $ tells the regex engine to only look at the end of the line for the matching pattern:

'ucp-1.1.0_dtr-2.0.0'[/[\d.]+$/] # => "2.0.0"

The Regexp documentation covers all this.