JP Silvashy
JP Silvashy

Reputation: 48485

matching a string in ruby with regex

I have the following line

'passenger (2.2.5, 2.0.6)'.match(//)[0]

which obviously doesn't match anything yet

I want to return the just the content of (2.2.5, so everything after the open parentheses and before the comma.

How would I do this?

Upvotes: 0

Views: 385

Answers (3)

szeryf
szeryf

Reputation: 3387

Beanish solution fails on more than 2 version numbers, you should use something like:

>> 'passenger (2.2.5, 2.0.6, 1.8.6)'.match(/\((.*?),/)[1] # => "2.2.5"

Upvotes: 2

Wayne Conrad
Wayne Conrad

Reputation: 107959

#!/usr/bin/env ruby

s = 'passenger (2.2.5, 2.0.6)'
p s.scan(/(?:\(|, *)([^,)]*)/).flatten    # => ["2.2.5", "2.0.6"]

Upvotes: 1

Beanish
Beanish

Reputation: 1662

'passenger (2.2.5, 2.0.6)'.match(/\((.*),/)[1]

if you use the $1 element it is the group that is found within the ( )

Upvotes: 1

Related Questions