简体   繁体   English

用正则表达式匹配红宝石中的字符串

[英]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. 我只想返回(2.2.5,的内容(2.2.5,因此在开括号后和逗号之前的所有内容。

How would I do this? 我该怎么做?

Beanish解决方案在两个以上的版本号上均失败,您应该使用类似以下的方法:

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

如果您使用$ 1元素,则是()中的组

#!/usr/bin/env ruby

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM