简体   繁体   English

Ruby正则表达式捕获gsub中的组

[英]Ruby regex capture groups in gsub

Say I want to switch each letter in a message with it's place in the reverse alphabet. 假设我想切换消息中的每个字母,并将其放在反向字母表中。 Why can't I seem to use the captured group and do it in one gsub? 为什么我似乎无法使用捕获的组并在一个gsub中执行此操作?

Perhaps someone could explain in general about using captured groups in gsub, can the back references be bare(no ' ')? 也许有人可以解释一下在gsub中使用捕获的组,可以反向引用是否裸露(没有'')? Can I use #{\\1}? 我可以使用#{\\ 1}吗?

def decode(message)
  a = ('a'..'z').to_a
  z = a.reverse
  message.gsub!(/([[:alpha:]])/, z[a.index('\1')]) 
end

decode("the quick brown fox")

Remember that arguments to methods are evaluated immediately and the result of that is passed in to the method. 请记住,立即计算方法的参数,并将结果传递给方法。 If you want to make the substitution adapt to the match: 如果你想让替换适应匹配:

message.gsub!(/([[:alpha:]])/) { |m| z[a.index($1)] }

That employs a block that gets evaluated for each match. 它使用一个块来评估每个匹配。

Using gsub : 使用gsub

Your code was not working because '\\1' is not yet being evaluated as its regex match, at the point you desire. 您的代码无效,因为'\\1'尚未被评估为其正则表达式匹配,在您需要的时候。 This can be solved by using a block, so the match variable is defined: 这可以通过使用块来解决,因此定义了匹配变量:

message.gsub(/[[:alpha:]]/) { |char| z[a.index(char)] }

Using tr : 使用tr

A more efficient way to solve problems like this, where you are simply "replacing one set of characters with another set", is to instead use String#tr . 解决这类问题的一种更有效的方法,就是使用String#tr来简单地“用另一组替换一组字符”。 This could be done as follows: 这可以按如下方式完成:

message.tr(a.join(''), z.join(''))

One way is to manipulate ASCII values. 一种方法是操纵ASCII值。

def code(message)
  message.gsub(/[[:alpha:]]/) { |s| (((s < 'a') ? 155 : 219 ) - s.ord).chr }
end

coded = code("the quick brown fox")
  #=> "gsv jfrxp yildm ulc" 
code(coded)
  #=> "the quick brown fox" 

Note: 注意:

'A'.ord + 'Z'.ord
  #=> 155 
'a'.ord + 'z'.ord
  #=> 219 

Another is to use a hash: 另一种是使用哈希:

a = ('a'..'z').to_a
Ch = a.zip(a.reverse).to_h
  #=> {"a"=>"z", "b"=>"y",..., "y"=>"b", "z"=>"a"} 

def code(message)
  message.gsub(/[[:alpha:]]/, Ch)
end

coded = code("the quick brown fox")
  #=> "gsv jfrxp yildm ulc"
code(coded)
  #=> "the quick brown fox"

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

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