meallhour
meallhour

Reputation: 15599

Getting substring value in Chef ruby

I have a string that has the following value:

ucp-1.1.0_dtr-2.0.0

I am trying to fetch only 1.1.0 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-','')

Upvotes: 0

Views: 1632

Answers (4)

night_nudt
night_nudt

Reputation: 1

Try this (verified):

"ucp-1.1.0_dtr-2.0.0".match(/^.-(.)_.-.$/)[1]

Upvotes: 0

the Tin Man
the Tin Man

Reputation: 160581

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.

Upvotes: 2

rohin-arka
rohin-arka

Reputation: 799

using regex with ruby string methods you can achieve this..

"ucp-1.1.0_dtr-2.0.0"

version = "ucp-1.1.0_dtr-2.0.0".scan(/[0-9_]/).join(".").split("_").first.slice(0..-2)

Or with your code you can try this..

substring = "ucp-1.1.0_dtr-2.0.0".gsub('ucp-','').split("_").first

Upvotes: 0

pjammer
pjammer

Reputation: 9577

substring = "ucp-1.1.0_dtr-2.0.0".gsub('ucp-','').split("_").first untried.

Upvotes: 0

Related Questions