我对 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/