ruby - 搜索/替换怪异

标签 ruby regex

为什么这段代码只修改数组中的最后一个文件?我的用户可以读取和写入这些文件。

%w(views/layout.rhtml views/admin/layout.rhtml).each do |file|
  text = File.read(file)
  File.open(file, 'w+') do |f|
    f << text.gsub(/\?v=(\d+)/, "?v=#{$1.to_i + 1}")
  end
end

最佳答案

您的问题是您没有使用 gsub 的 block 形式所以$1并且类似的全局变量并不像您想象的那样设置。来自精美手册:

If replacement is a String it will be substituted for the matched text. It may contain back-references to the pattern‘s capture groups of the form \\d, where d is a group number, or \\k<n>, where n is a group name. If it is a double-quoted string, both back-references must be preceded by an additional backslash. However, within replacement the special match variables, such as &$, will not refer to the current match.

还有:

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. The value returned by the block will be substituted for the match on each call.

大胆的我的。另外,我省略了全局反引号:

$`

为了避免 Markdown 出现问题(如果有人知道如何在内联代码块中获得反引号,我将不胜感激)。

如果您这样做:

%w(views/layout.rhtml views/admin/layout.rhtml).each do |file|
  text = File.read(file)
  File.open(file, 'w+') do |f|
    f << text.gsub(/\?v=(\d+)/) { "?v=#{$1.to_i + 1}" }
  end
end

我想您会得到您正在寻找的结果。

关于ruby - 搜索/替换怪异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6577165/

相关文章:

java - 正则表达式检查字符串仅包含十六进制字符

regex - 在这些 Perl 单行代码中会发生什么?

javascript - Ruby Hpricot RegEx 替换 <BR >'s with <P>' s

jquery - 如果不存在,则将 `http://` 添加到字符串中

javascript - 从 Javascript 到 PHP 的正则表达式

ruby - Libxml2 缺少 mac os x 10.10

ruby - codecademy 在这里错了吗?

ruby - Ruby 中的递归斐波那契数列

ruby - 哪个 gem 更适合用于 rails 4 中的天气馈送?

ruby - 避免使用相同的用户名和密码多次登录