2014-01-06 3 views
1

다음 코드 from Ruby Quiz website을 이해하려고합니다.madlib.gsub! ( ( s (*) s * ) ) /, "<% = q_to_a ('\ 1') %>"에서 \ 1의 의미

'\\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 
+0

이'(. +?)'부분의 'Regexp'. '\ 1','\ 2' 등은': gsub'가 사용되지 않을 때'$ 1','$ 2' 등과 같이 결과 괄호의 값을 얻습니다. –

+0

답변이 도움이 되었습니까? –

답변

1

두 개의 동일한 단어가 공백으로 구분 된 문자열을 찾고 있다고 가정 해보십시오. (.+?)\s을 작성하여 시작할 수도 있지만 첫 번째 괄호 세트와 일치하는 내용을 나타내는 방법이 필요합니다. 이것은 정확히 \n (또는 \\n)입니다. n 번째 괄호 세트의 내용을 나타냅니다. 다른이 지적으로 "ab cd ef ef gh ik"에서 "ef ef"하면, 특정 경우에는 다음과 같은 정규식 표현을

(.+?)\s\1 

를 사용할 수 추출하고자한다면 그래서, \\1(.+?)의 내용에 구체적으로 언급한다. 다른 모든 괄호 뒤에는 텍스트의 실제 괄호와 일치하는 이스케이프 문자가 있기 때문에 고려되지 않습니다.

0

1Regexp(.+?) 부분에서 온다. :gsub 또는 블록 또는 교체가있는 다른 방법을 사용하지 않는 경우 \1, \2 등은 결과로 나오는 괄호에서 값을 얻습니다. $1, $2

관련 문제