Created
September 1, 2010 20:22
-
-
Save sandropaganotti-zz/561286 to your computer and use it in GitHub Desktop.
[QUIZ] Fiddle with regular expressions (#2)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#= part 1 | |
reg = | |
/^ | |
[\w!#\$%&'*+\/=?`{|}~^-]+ # 1 or more glyph of: underscore alphabetic letters and symbols choosed from !#\$%&'*+\/=?`{|}~^- | |
# followed by | |
(?:\. # a non-catching block wich has to begin with a dot followed by | |
[\w!#\$%&'*+\/=?`{|}~^-]+ # 1 or more gliyp of the same class of line 3. | |
)* # this block can apper 0 or more times. | |
@ # followed by an 'at' sign | |
(?: # followed by a non-catching block containing | |
[a-zA-Z0-9-]+ # a sequence of 1 or more lowercase or uppercase alphanumeric chars | |
\.)+ # ending with a dot. The whole block has to be present 1 ore more times in the string | |
# followed by | |
[a-zA-Z]{2,6} # 2 to 6 chars of lowercase or uppercase alphabetic chars | |
$/x | |
puts 'jd@example.com'[reg] # => jd@example.com | |
puts 'jd@example.tooolong'[reg] # => nil | |
puts 'j*d@example.com'[reg] # => j*d@example.com | |
puts 'john.doe@example.com.INFO'[reg] # => john.doe@example.com.INFO | |
puts 'jd.@example.com'[reg] # => nil | |
#= part 2 | |
reg_w_named_refs = /^ | |
(?<username_token> [\w!#\$%&'*+\/=?`{|}~^-]+ ){0} | |
(?<domain_token> [a-zA-Z0-9-]+ ){0} | |
(?<ext_token> [a-zA-Z]{2,6} ){0} | |
\g<username_token>(?:\.\g<username_token>)*@(?:\g<domain_token>\.)+\g<ext_token> | |
$/x | |
puts 'jd@example.com'[reg_w_named_refs] # => jd@example.com | |
puts 'jd@example.tooolong'[reg_w_named_refs] # => nil | |
puts 'j*d@example.com'[reg_w_named_refs] # => j*d@example.com | |
puts 'john.doe@example.com.INFO'[reg_w_named_refs] # => john.doe@example.com.INFO | |
puts 'jd.@example.com'[reg_w_named_refs] # => nil | |
#= part 3 | |
reg_anti_evil_hacker = | |
/\A | |
[\w!#\$%&'*+\/=?`{|}~^-]+ | |
(?:\. | |
[\w!#\$%&'*+\/=?`{|}~^-]+ | |
)* | |
@ | |
(?: | |
[a-zA-Z0-9-]+ | |
\.)+ | |
[a-zA-Z]{2,6} | |
\Z/x | |
puts "<script>alert('boo');</script>\nevil@hacker.com"[reg] # =>evil@hacker.com | |
puts "<script>alert('boo');</script>\nevil@hacker.com"[reg_anti_evil_hacker] # =>nil | |
#= part 4 | |
def encrypt(string) | |
string.gsub(/([[:alnum:]])/){|m|m.next} | |
end | |
puts encrypt("this is a test") # => uijt jt b uftu |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment