tags:

views:

62

answers:

3

I'm pretty bad with regex... well I'm learning that is :)

I have the following line (which needs a regex guru's help):

'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?

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

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

Beanish
I think you forgot a `/\` 'passenger (2.2.5, 2.0.6)'.match(/\((.*),/)[0]
Joseph Silvashy
thanks! I guess it was a little easier than I thought!
Joseph Silvashy
use a tool like http://rubular.com/ or http://www.gskinner.com/RegExr/ to test your regex online
Beanish
this is greedy matching, it will eat everything until _last_ comma, so when there are more than 2 versions it will return all but last.check this out:>> 'passenger (2.2.5, 2.0.6, 1.8.6)'.match(/\((.*),/)[1]=> "2.2.5, 2.0.6"
szeryf
+2  A: 

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"
szeryf
you are correct.
Joseph Silvashy
if only . and 0-9 are valid, you can even get more specific/\(([\.0-9]*),/
Beanish
szeryf, that regex got garbled in formatting, I think. It's got mismatched parentheses as it appears in my browser: /((.*?),/
Wayne Conrad
Also `/\(([^,]),/` or `/\(([.\d]),/` should work.
kejadlen
Wayne Conrad: you're right, I fixed this. Thanks.
szeryf
+1  A: 
#!/usr/bin/env ruby

s = 'passenger (2.2.5, 2.0.6)'
p s.scan(/(?:\(|, *)([^,)]*)/).flatten    # => ["2.2.5", "2.0.6"]
Wayne Conrad
ooh this is nice.
Joseph Silvashy