Regular Expressions: /regex Will Find Me
Regular Expressions: /regex Will Find Me
pattern. Replace part of a string with another string. Split a string based on a matching separator.
Regex Basics
[abc] A single character: a, b or c
(a|b) a or b
a? Zero or one of a a* Zero or more of a a+ One or more of a a{3} Exactly 3 of a a{3,} 3 or more of a a{3,6} Between 3 and 6 of a
Regex: .match
>> category = "power tools" => "power tools" >> puts "on Sale" if category.match(/power tools/) on Sale >> puts "on Sale" if /power tools/.match(category) on Sale
Regex: =~
>> category = "shoes" => "shoes" >> puts "15 % off" if category =~ /shoes/ 15 % off >> puts "15 % off" if /shoes/ =~ category 15 % off >> /pants/ =~ category => nil >> /shoes/ =~ category => 0 >> category = "women's shoes >> /shoes/ =~ category => 8
8th character
Scan
>> numbers = "one two three" => "one two three" >> numbers.scan(/\w+/) => ["one", "two", "three]
gsub
fred,mary,john".gsub(/fred/, XXX) => XXX,mary,john
Title Case
Capitalize All Words of a Sentence: >> full_name.gsub(/\b\w/){|s| s.upcase} => "Yukihiro Matsumoto"