Ruby Regexp 组匹配,在 1 行分配变量 [英] Ruby Regexp group matching, assign variables on 1 line

查看:37
本文介绍了Ruby Regexp 组匹配,在 1 行分配变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试将一个字符串重新表示为多个变量.示例字符串:

I'm currently trying to rexp a string into multiple variables. Example string:

ryan_string = "RyanOnRails: This is a test"

我已经将它与这个正则表达式匹配,有 3 个组:

I've matched it with this regexp, with 3 groups:

ryan_group = ryan_string.scan(/(^.*)(:)(.*)/i)

现在要访问每个组,我必须执行以下操作:

Now to access each group I have to do something like this:

ryan_group[0][0] (first group) RyanOnRails
ryan_group[0][1] (second group) :
ryan_group[0][2] (third group) This is a test

这看起来很可笑,感觉就像我做错了什么.我希望能够做这样的事情:

This seems pretty ridiculous and it feels like I'm doing something wrong. I would be expect to be able to do something like this:

g1, g2, g3 = ryan_string.scan(/(^.*)(:)(.*)/i)

这可能吗?或者有比我现在做的更好的方法吗?

Is this possible? Or is there a better way than how I'm doing it?

推荐答案

您不希望 scan 这样做,因为它毫无意义.您可以使用 String#match 返回一个 MatchData 对象,然后您可以调用 #captures 返回一个捕获数组.像这样:

You don't want scan for this, as it makes little sense. You can use String#match which will return a MatchData object, you can then call #captures to return an Array of captures. Something like this:

#!/usr/bin/env ruby

string = "RyanOnRails: This is a test"
one, two, three = string.match(/(^.*)(:)(.*)/i).captures

p one   #=> "RyanOnRails"
p two   #=> ":"
p three #=> " This is a test"

请注意,如果未找到匹配项,String#match 将返回 nil,因此这样的操作可能会更好:

Be aware that if no match is found, String#match will return nil, so something like this might work better:

if match = string.match(/(^.*)(:)(.*)/i)
  one, two, three = match.captures
end

尽管 scan 对此没有多大意义.它仍然可以完成这项工作,您只需要先展平返回的 Array.一、二、三 = string.scan(/(^.*)(:)(.*)/i).flatten

Although scan does make little sense for this. It does still do the job, you just need to flatten the returned Array first. one, two, three = string.scan(/(^.*)(:)(.*)/i).flatten

这篇关于Ruby Regexp 组匹配,在 1 行分配变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆