我正在使用带有正则表达式的 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/