我试图理解下面的代码来自Ruby网站。
我没有得到'\\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发布于 2014-01-26 09:33:32
假设您正在寻找一个字符串,该字符串包含两个由空白分隔的相同单词。您可以从编写(.+?)\s开始,但是您需要某种方法来表示与第一组括号匹配的相同内容。这正是\n (或\\n)所做的。它指的是第n组括号的内容。因此,如果要从"ef ef"中提取"ab cd ef ef gh ik",可以使用以下正则表达式
(.+?)\s\1在您的特定情况下,正如其他人所指出的,\\1具体指的是(.+?)的内容。请注意,所有其他括号前面都有转义字符,以便与文本中的实际括号相匹配,因此没有考虑到它们。
发布于 2014-01-06 12:47:51
这意味着正则表达式或这个块(.+?)上的第一个匹配组。
看看这个来帮助你的理解:http://www.regular-expressions.info/named.html
发布于 2014-01-06 12:58:34
1来自Regexp的这个(.+?)部分。如果不使用\1或其他带块或替换的方法,则\2、:gsub等将从相应的括号以及$1、$2等获得值。
https://stackoverflow.com/questions/20949750
复制相似问题