ruby - 提取正则表达式中的字符串

标签 ruby regex string

我对 Ruby 有点陌生,但我对 Ruby 中的正则表达式有疑问。

我有一个字符串,我想将字符串中的数字保存在新变量中,并且只保存数字。 ruby 是一种粉红色到血红色的 gem ,是刚 Jade 矿物(氧化铝)的变种。 我的文字是

ruby is a pink to blood-red colored gemstone, a variety8of the mineral corundum (aluminium oxide). 

我的正则表达式是:

/blood-red colored gemstone, a variety(.*?)of the mineral corundum/m

现在我想将结果保存在一个新变量中。所以我们可以说:

var1 = 'ruby is a pink to blood-red colored gemstone, a variety8of the mineral corundum (aluminium oxide).'

var2 = var1[/blood-red colored gemstone, a variety(.*?)of the mineral corundum/m]

现在的结果是整个句子从血红色...到...矿物刚 Jade 。 但我怎样才能无边界地进入中间。在 Rubular 中,它显示为一个“组”(在我的例子中,我想访问句子内的数字)。我如何才能访问该群组?

您可以在 Rubular 中观看我的示例 http://rubular.com/r/PgAgwRw3a5

非常感谢

最佳答案

来自documentation :

If a Regexp is supplied, the matching portion of the string is returned. If a capture follows the regular expression, which may be a capture group index or name, follows the regular expression that component of the MatchData is returned instead.

所以,这应该有效:

 var2 = var1[/blood-red colored gemstone, a variety(.*?)of the mineral corundum/m, 1]
 # => "8"

关于ruby - 提取正则表达式中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26926261/

相关文章:

python - 从系列和字符串创建数据框

java - 包含纬度的字符串转换为普通数字

ruby - 无法设置 ruby​​ 环境 - 安装 fii gem 错误

regex - perl 中正则表达式匹配的奇怪问题,替代尝试匹配

Javascript 常规异常在 Chrome 和 Firefox 中每两次尝试匹配一次字符串

python - 如何使用正则表达式在 Python 3 中的特定字符串之后或之前找到一行?

c++ - 使用strtok按条件拆分字符串?

ruby 正则表达式 : capture the path of url

ruby-on-rails - Ruby on Rails 表单输入

javascript - 在 Rails 中使用相同模型验证两种表单的参数