简体   繁体   English

有没有办法将正则表达式捕获传递给Ruby中的块?

[英]Is there a way to pass a regex capture to a block in Ruby?

I have a hash with a regex for the key and a block for the value. 我有一个带有regex的哈希值和一个值的block Something like the following: 类似于以下内容:

{ 'test (.+?)' => { puts $1 } }

Not exactly like that, obviously, since the block is being stored as a Proc, but that's the idea. 完全是这样的,很明显,因为该块被存储为一个Proc,但是这想法。

I then have a regex match later on that looks a lot like this 然后,我之后进行了正则表达式匹配,看起来很像这样

hash.each do |pattern, action|
    if /#{pattern}/i.match(string)
        action.call
    end
end

The idea was to store the block away in the hash to make it a bit easier for me to expand upon in the future, but now the regex capture doesn't get passed to the block. 我的想法是将块存储在哈希中,以便我将来更容易扩展,但现在regex捕获不会传递给块。 Is there a way to do this cleanly that would support any number of captures I put in the regex (as in, some regex patterns may have 1 capture, others may have 3)? 有没有办法干净利落地支持我在regex放置的任何数量的捕获(例如,一些regex模式可能有1个捕获,其他可能有3个)?

What if you pass the match data into your procs? 如果您将匹配数据传递到您的过程中该怎么办?

hash.each do |pattern, action|
  if pattern.match(string)
    action.call($~)
  end
end

Your hash would become: 你的哈希会成为:

{ /test (.+?)/i => lambda { |matchdata| puts matchdata[1] } }

I would use Hash.find which walks the hash elements, passing them into a block, one at a time. 我会使用散列哈希元素的Hash.find ,将它们一次一个地传递给一个块。 The one that returns true wins: 返回true那个获胜:

Something like this: 像这样的东西:

hash = {/foo/ => lambda { 'foo' }, /bar/ => lambda { 'bar' } }
str = 'foo'
puts hash.find{ |n,v| str =~ n }.to_a.last.call

Obviously I'm using lambda but it's close enough. 显然我正在使用lambda但它足够接近。 And, if there was no match you need to handle nil values. 并且,如果没有匹配,则需要处理nil值。 For the example I chained to_a.last.call but in real life you'd want to react to a nil otherwise Ruby will get mad. 举个例子,我链接到了to_a.last.call但在现实生活中,你想要对nil做出反应,否则Ruby会生气。

If you are searching through a lot of patterns, or processing a lot of text, your search will be slowed down by having to recompile the regex each time. 如果您正在搜索大量模式或处理大量文本,则每次必须重新编译正则表达式时,搜索速度会变慢。 I'd recommend storing the keys as regex objects to avoid that. 我建议将密钥存储为正则表达式对象以避免这种情况。

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

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