madlib.gsub中\\ 1的含义!(/ \(\(\ s *(。+?)\ s * \)\)/,“<%= q_to_a('\\ 1')%>” )

时间:2014-01-06 12:09:20

标签: ruby parameters

我正在尝试理解以下代码from Ruby Quiz website

我没有得到'\\1'中的madlib.gsub!(/\(\(\s*(.+?)\s*\)\)/, "<%= q_to_a('\\1') %>")部分,这是底部的第三行。

'\\1'逃脱了吗? 1来自哪里?

我提前感谢你。

这是整个代码。

#!/usr/local/bin/ruby -w
#---
# Excerpted from "Best of Ruby Quiz"
# We make no guarantees that this code is fit for any purpose. 
# Visit http://www.pragmaticprogrammer.com/titles/fr_quiz for more book information.
#---

# use Ruby's standard template engine
require "erb"

# storage for keyed question reuse
$answers = Hash.new

# asks a madlib question and returns an answer
def q_to_a( question )
  question.gsub!(/\s+/, " ")       # normalize spacing

  if $answers.include? question    # keyed question
    $answers[question]
  else                             # new question
    key = if question.sub!(/^\s*(.+?)\s*:\s*/, "") then $1 else nil end

    print "Give me #{question}:  "
    answer = $stdin.gets.chomp

    $answers[key] = answer unless key.nil?

    answer
  end
end

# usage
unless ARGV.size == 1 and test(?e, ARGV[0])
  puts "Usage:  #{File.basename($PROGRAM_NAME)} MADLIB_FILE"
  exit  
end

# load Madlib, with title
madlib = "\n#{File.basename(ARGV.first, '.madlib').tr('_', ' ')}\n\n" +
         File.read(ARGV.first)
# convert ((...)) to <%= q_to_a('...') %>
madlib.gsub!(/\(\(\s*(.+?)\s*\)\)/, "<%= q_to_a('\\1') %>")
# run template
ERB.new(madlib).run

3 个答案:

答案 0 :(得分:1)

假设您正在寻找包含两个由空格分隔的相同单词的字符串。您可以从编写(.+?)\s开始,但是您需要某种方式来表示与第一组括号匹配的相同内容。这正是\n(或\\n)的作用。它指的是第n组括号的内容。因此,如果您想从"ef ef"中提取"ab cd ef ef gh ik",可以使用以下正则表达式

(.+?)\s\1

在您的特定情况下,正如其他人所指出的,\\1特指(.+?)的内容。请注意,所有其他括号前面都有转义字符,以匹配文本中的实际括号,因此不会将它们考虑在内。

答案 1 :(得分:0)

这意味着您的正则表达式或此块(.+?)上的第一个匹配组。

请看一下这有助于您理解:http://www.regular-expressions.info/named.html

答案 2 :(得分:0)

1来自(.+?)的{​​{1}}部分。当没有Regexp或其他方法时,\1\2等从括号中得到一个值,以及$1$2等等。使用阻止或替换。