ubuntu, ror, jQuery, css, website memo
太嫩, 沒啥心得, 用來紀錄每天學的
2009年1月9日 星期五
字串 String 一些好用的 function, scan, split, match, gsub, sub
Scan
=begin
a = "cruel world"
a.scan(/\w+/) #=> ["cruel", "world"]
a.scan(/.../) #=> ["cru", "el ", "wor"]
a.scan(/(...)/) #=> [["cru"], ["el "], ["wor"]]
a.scan(/(..)(..)/) #=> [["cr", "ue"], ["l ", "wo"]]
$` before match string
$' after match string
$& entire match string
=end
>> "111111222222333".scan(/....../).push($')
=> ["111111", "222222", "333"]
def wbr_by_6(long_word)
if long_word.chars.size > 6
long_word.scan(/....../).push($').map{|m| CGI.escapeHTML(m)}.join('
')
else
CGI.escapeHTML(long_word)
end
end
def format_content(content)
def sub_url(text)
if text =~ URI.regexp && $&[0,4] == 'http'
"#{$`}
#{wbr_by_6($&)}
#{sub_url($')}"
else
#content = CGI.escapeHTML(content)
wbr_by_6(text)
end
end
sub_url(content)
end
Split
" now's the time".split #=> ["now's", "the", "time"]
" now's the time".split(' ') #=> ["now's", "the", "time"]
" now's the time".split(/ /) #=> ["", "now's", "", "the", "time"]
"1, 2.34,56, 7".split(%r{,\s*}) #=> ["1", "2.34", "56", "7"]
"hello".split(//) #=> ["h", "e", "l", "l", "o"]
"hello".split(//, 3) #=> ["h", "e", "llo"]
"hi mom".split(%r{\s*}) #=> ["h", "i", "m", "o", "m"]
"mellow yellow".split("ello") #=> ["m", "w y", "w"]
"1,2,,3,4,,".split(',') #=> ["1", "2", "", "3", "4"]
"1,2,,3,4,,".split(',', 4) #=> ["1", "2", "", "3,4,,"]
"1,2,,3,4,,".split(',', -4) #=> ["1", "2", "", "3", "4", "", ""]
Match and Scan 感受一下啥時要用啥吧
MESSAGE_REGEX = /^([@#&?$\/>])\s*([^\s]+)\s*(\w*)/
>> MESSAGE_REGEX.match("@lake lalaa ").to_a
=> ["@lake lalaa", "@", "lake", "lalaa"]
>> MESSAGE_REGEX.match("@lake lalaa 123").to_a
=> ["@lake lalaa", "@", "lake", "lalaa"]
array 傳回的第一個是整個match 的部份, 後面是()的部份
>> MESSAGE_REGEX.match("@lake lalaa 123").to_a.push($')
=> ["@lake lalaa", "@", "lake", "lalaa", " 123"]
跟scan 很像吧, 玩玩有啥不同
>> "@lake lalaa 123".scan(MESSAGE_REGEX)
=> [["@", "lake", "lalaa"]]
>> "@lake lalaa 123".scan(MESSAGE_REGEX).push($')
=> [["@", "lake", "lalaa"], " 123"]
外面又包了一層 Array
把regexp 的()拿掉
>> MESSAGE_REGEX = /^[@#&?$\/>]\s*[^\s]+\s*\w*/
(irb):57: warning: already initialized constant MESSAGE_REGEX
=> /^[@#&?$\/>]\s*[^\s]+\s*\w*/
>> "@lake lalaa 123".scan(MESSAGE_REGEX).push($')
=> ["@lake lalaa", " 123"]
gsub and sub 就是 replace 只是一個全部, 一個只有第一個
"hello".gsub(/[aeiou]/, '*') #=> "h*ll*"
"hello".gsub(/([aeiou])/, '<\1>') #=> "h
ll
"
"hello".gsub(/./) {|s| s[0].to_s + ' '} #=> "104 101 108 108 111 "
沒有留言:
張貼留言
較新的文章
較舊的文章
首頁
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言