2008年11月12日 星期三

regexp,uri,cgi,encode,decode

http://snippets.dzone.com/posts/show/5180
http://ruby-doc.org/stdlib/libdoc/uri/rdoc/classes/URI/Escape.html#M009386
http://ruby-doc.org/stdlib/libdoc/cgi/rdoc/classes/CGI.html#M000091

[^abc]
Any single character but a, b, or c


1
2 require 'cgi'
3
4 # escape
5 name = "ruby?"
6 value = "yes"
7 url = "http://example.com/?" + CGI.escape(name) + '=' + CGI.escape(value) + "&var=T"
8 # url: http://example.com/?ruby%3F=yes&var=T
9 html = %(<a href="#{CGI.escapeHTML(url)}">example</a>)
10 # html: <a href="http://example.com/?ruby%3F=yes&amp;var=T">example</a>
11
12 # unescape
13 name_encoded = html.match(/http:([^"]+)/)[0]
14 # name_encoded: http://example.com/?ruby%3F=yes&amp;var=T
15 href = CGI.unescapeHTML(name_encoded)
16 # href: http://example.com/?ruby%3F=yes&var=T
17 query = href.match(/\?(.*)$/)[1]
18 # query: ruby%3F=yes&var=T
19 pairs = query.split('&')
20 # pairs: ["ruby%3F=yes", "var=T"]
21 name, value = pairs[0].split('=').map{|v| CGI.unescape(v)}
22 # name, value: ["ruby?", "yes"]

沒有留言: