简体   繁体   English

ruby regex扫描和gsub与块中的捕获组的工作方式不同

[英]ruby regex scan and gsub work differently with capture groups in blocks

I have a string of alternating digits and letters. 我有一串交替的数字和字母。 I want to replace each character with the number of letters preceding it. 我想用前面的字母数替换每个字符。 For example, 2a3b should return aabbb . 例如, 2a3b应该返回aabbb

First, If I do: 首先,如果我这样做:

"2a3b".scan(/(\d)(.)/) do |count, char|
  puts char * count.to_i
end 

I get: 我得到:

aa
bbb

But, if I do: 但是,如果我这样做:

"2a3b".gsub(/(\d)(.)/) do |count, char|
  char * count.to_i
end 

I get an error: 我收到一个错误:

NoMethodError: undefined method `*' for nil:NilClass

Shouldn't they both behave the same (Update: I mean, accept capture groups as block params)? 它们的行为不应该一样吗(更新:我的意思是,接受捕获组作为块参数)?

Update : (workaround, which works) 更新 :(替代方法,可行)

"2a3b".gsub(/(\d)(.)/) do |match|
  $2 * $1.to_i
end 

returns: 收益:

"aabbb"

as expected. 如预期的那样。

No they don't behave the same. 不,他们的行为不同。 The block form of gsub only accepts one parameter, so the second is going to be nil, hence your error. gsub的块形式仅接受一个参数,因此第二个参数将为nil,因此会出现错误。 See http://ruby-doc.org/core-2.1.4/String.html#method-i-gsub 参见http://ruby-doc.org/core-2.1.4/String.html#method-i-gsub

Example of use: "hello".gsub(/./) {|s| s.ord.to_s + ' '} 使用示例: "hello".gsub(/./) {|s| s.ord.to_s + ' '} "hello".gsub(/./) {|s| s.ord.to_s + ' '}

In the block form, the current match string is passed in as a parameter, and variables such as $1, $2, $`, $&, and $' will be set appropriately. 在块形式中,当前的匹配字符串作为参数传递,并且诸如$ 1,$ 2,$`,$&和$'之类的变量将被适当地设置。 The value returned by the block will be substituted for the match on each call. 该块返回的值将代替每次调用的匹配项。

The result inherits any tainting in the original string or any supplied replacement string. 结果将继承原始字符串或任何提供的替换字符串中的任何污点。

No, they are two different methods and do different things. 不,它们是两种不同的方法,它们执行不同的操作。

See http://ruby-doc.org/core-2.2.2/String.html#gsub-method and http://ruby-doc.org/core-2.2.2/String.html#scan-method 参见http://ruby-doc.org/core-2.2.2/String.html#gsub-methodhttp://ruby-doc.org/core-2.2.2/String.html#scan-method

In the abstract, scan is more for finding patterns in strings/expressions, (and with a block, formatting them in some way) while gsub is more about doing replacements on patterns in a string. 简而言之,扫描更多的是在字符串/表达式中查找模式(并使用一个块,以某种方式对其进行格式化),而gsub的更多内容是对字符串中的模式进行替换。

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

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