ruby - 如何用 MatchData 对象替换 Perl 风格的正则表达式

标签 ruby regex rubocop

我正在使用带有正则表达式的 gsub 方法:

@text.gsub(/(-\n)(\S+)\s/) { "#{$2}\n" }

输入数据示例:

"The wolverine is now es-
sentially absent from 
the southern end
of its European range."

应该返回:

"The wolverine is now essentially
absent from  
the southern end
of its European range."

该方法工作正常,但 rubocop 报告和冒犯:

Avoid the use of Perl-style backrefs.

关于如何使用 MatchData 对象而不是 $2 重写它有什么想法吗?

最佳答案

如果你想使用Regexp.last_match :

@text.gsub(/(-\n)(\S+)\s/) { Regexp.last_match[2] + "\n" }

或:

@text.gsub(/-\n(\S+)\s/) { Regexp.last_match[1] + "\n" }

注意gsub中的block在涉及逻辑的时候要用到。如果没有逻辑,将第二个参数设置为 "\\1\n"'\1' + "\n" 就可以了。

关于ruby - 如何用 MatchData 对象替换 Perl 风格的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43510068/

相关文章:

ruby - Ruby 如何允许方法参数默认值从早期参数派生?

ruby - 在 Ruby 中解析 JSON 字符串

c# - 正则表达式生成

ruby - Rubocop 25 行 block 大小和 RSpec 测试

ruby-on-rails - Rubocop 和 capybara : detecting forgotten focus: :true

ruby-on-rails - Ruby:平均时间数组

ruby-on-rails - 带关键字参数的意外 tIDENTIFIER

python - 如何使用Python正则表达式处理zookeeper日志文件?

Javascript replace() 正则表达式太贪心了

ruby-on-rails - 此方法如何超过 Rubocop 帐户分支条件大小?