Ruby/Development/Regexps Group

Материал из Wiki.crossplatform.ru

(Различия между версиями)
Перейти к: навигация, поиск
м (1 версия: Импорт выборки материалов по Ruby)
 

Текущая версия на 17:55, 13 сентября 2010

Содержание

\1 refers to the match of the first group

# \2 the second group,and so on.
# Outside the pattern,the special variables $1, $2, and so on, serve the samepurpose. 
"12:50am" =~ /(\d\d):(\d\d)(..)/ # 0 
"Hour is #$1, minute #$2" # "Hour is 12, minute 50" 
"12:50am" =~ /((\d\d):(\d\d))(..)/ # 0 
"Time is #$1" # "Time is 12:50" 
"Hour is #$2, minute #$3" # "Hour is 12, minute 50" 
"AM/PM is #$4" # "AM/PM is am"



An unescaped vertical bar(|) matches either the regular expression that precedes it or the regular expression that follows it.

def show_regexp(a, re) 
    if a =~ re 
        "#{$`}<<#{$&}>>#{$"}"  
    else 
        "no match" 
    end 
end 
a = "this is a test" 
show_regexp(a, /d|e/) 
show_regexp(a, /al|lu/)
show_regexp(a, /is test|this is/)



Backslash Sequences in the Substitution

"fred:smith".sub(/(\w+):(\w+)/, "\2, \1") # "smith, fred" 
"nercpyitno".gsub(/(.)(.)/, "\2\1") # "encryption"



unescape HTML

def unescapeHTML(string) 
    str = string.dup 
    str.gsub!(/&(.*?);/n) { 
        match = $1.dup 
        case match 
        when /\Aamp\z/ni then "&" 
        when /\Aquot\z/ni then """ 
        when /\Agt\z/ni then ">" 
        when /\Alt\z/ni then "<" 
        when /\A#(\d+)\z/n then Integer($1).chr 
        when /\A#x([09af]+)\z/ni then $1.hex.chr 
        end 
    } 
    str 
end 
puts unescapeHTML("1&lt;2 &amp;&amp; 4&gt;3") 
puts unescapeHTML("&quot;A&quot; = &#65; = &#x41;")



use parentheses to group terms within a regular expression

# Everything within the group is treated as a single regular expression. 
def show_regexp(a, re) 
    if a =~ re 
        "#{$`}<<#{$&}>>#{$"}" 
    else 
        "no match" 
    end 
end 
show_regexp("banana", /an*/) # b<<an>>ana 
show_regexp("banana", /(an)*/) # <<>>banana 
show_regexp("banana", /(an)+/) # b<<anan>>a