SlideShare uma empresa Scribd logo
1 de 35
Class 4 Regular Expressions & Enumerables
Regular Expressions /regex will find me/
What are Regular Expressions Regular expressions allow matching and manipulation of textual data. Abbreviated as regex or regexp, or alternatively, just patterns
What are Regular Expressions For?	 Scan a string for multiple occurrences of a pattern. Replace part of a string with another string. Split a string based on a matching separator.
Regular Expressions in Ruby ,[object Object]
 They are escaped with a backward slash (.,[object Object]
Regex Basics [abc] A single character: a, b or c  [^abc] Any single character but a, b, or c  [a-z] Any single character in the range a-z  [a-zA-Z] Any single character in the range a-z or A-Z  ^ Start of line  $ End of line   Start of string   End of string
Regex Basics cont... . Any single character   Any whitespace character   Any non-whitespace character   Any digit   Any non-digit   Any word character (letter, number, underscore)   Any non-word character   Any word boundary character
Regex Basics cont... (...) Capture everything enclosed  (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(/+/) => ["one", "two", "three”]
Split with Regular Expressions >> "one twothree".split(//) => ["one", ”two", "three"]
gsub ”fred,mary,john".gsub(/fred/, “XXX”) => “XXX,mary,john”
gsub with a block "one twothree".gsub(/(+)/) do |w| 	puts w end one two three
Title Case Capitalize All Words of a Sentence: >> full_name.gsub(//){|s| s.upcase} => "Yukihiro Matsumoto"
Live Coding Example Scraping Thentic.com
Enumerables Collection Behavior
Why Use Enumerables Ruby's Enumerable module has methods for all kinds of tasks.  If you can imagine a use for the #each method other than simply iterating, there is a good chance a method exists to do what you have in mind.
What does Enumerable Mean? Collection objects (instances of Array, Hash, etc) typically “mixin” the Enumerable module The Enumerable module gives objects of collection classes additional collection-specific behaviors. The class requiring the Enumerable module must have an #each method because the additional collection-specific behaviors given by Enumerable are defined in terms of #each
Mixing in Enumerable class MyCollection 	include Enumerable 	#lots of code 	def each 		#more code 	end end
View all Classes Mixing in Enumerable ObjectSpace.each_object(Class) do |cl|  		puts cl if cl < Enumerable end
Enumerable::Enumerator Struct::Tms Dir File IO Range Struct Hash Array String Struct::Group Struct::Passwd MyCollection StringIO Gem::SourceIndex YAML::Set YAML::Pairs YAML::Omap YAML::SpecialHas
Test an Instance or Class  >> a = [1,2,3] => [1, 2, 3] >> a.respond_to? :any? => true >> a.is_a? Enumerable => true >> Array < Enumerable => true
each Classes that include the Enumerable module must have an #each method.  The #each method yields items to a supplied code block, one at a time Different Classes define #each differently Array: #each yields each element Hash: each yields #each key/value pair as a two-element array >> v_names = %w(car truck bike) => ["car", "truck", "bike"] >> v_names.each do |vehicle| ?> puts vehicle >> end
map The map method modifies each member according to instructions in a block and returns the modified collection of members. >> v_names.map { |v| v.upcase} => ["CAR", "TRUCK", "BIKE"]
grep The grep method 'searches' for members using a regular expression.  >> v_names.grep /a/ => ["car"] >> v_names.grep(/a/) { |v| v.upcase} => ["CAR"]
find >> v_names.find { |v| v.size > 3} => "truck" >> v_names.find { |v| v.size > 2} => "car" >> v_names.find do |v|  v.size > 3 && v.size < 5 end => "bike"
all? The all? method returns true if all of the members of a collection satisfy the evaluation of the block.  Otherwise it returns false. >> v_names.all? { |v| v.length > 2} => true >> v_names.all? { |v| v.length > 10} => false
any? The any? method returns true if any of the members of a collection satisfy the evaluation of the block.  Otherwise it returns false. >> v_names.any? { |v| v.length == 3} => true >> v_names.any? { |v| v = "car"} => true
Working with Complex Data irb >> load 'vehicles.rb' => true
inject >> $vehicles.inject(0) do |total_wheels, v| ?> total_wheels += v[:wheels] >> end => 10 >> $vehicles.inject([]) do |classes, v| ?> classes += v[:classes] >> end.uniq => [:ground, :water, :air]
Complex Operations >> $vehicles.find do |v| ?> v[:name] =~ /Plane/ >> end[:name] => "Plane" >> $vehicles.find_all do |v| ?> v[:name] =~ /Plane/ >> end.collect { |v| v[:name] } => ["Plane", "Sea Plane"] >> $vehicles.find_all do |v| ?> v[:wheels] > 0  >> end.collect { |v| v[:name] } => ["Car", "Truck", "Bike"]
Complex Operations Continued >> $vehicles.find_all do |v| ?> v[:classes].include? :ground >> end.collect { |v| v[:name] } => ["Car", "Truck", "Bike", "Sea Plane"] >> $vehicles.find_all do |v| ?> v[:classes].include? :air >> end.collect { |v| v[:name] } => ["Plane", "Helicopter", "Sea Plane"]
Homework Chapters: 10.1 – 10.8 11.1 -11.8

Mais conteúdo relacionado

Destaque

3 Strings Symbols
3 Strings Symbols3 Strings Symbols
3 Strings Symbols
liahhansen
 
6 Modules Inheritance Gems
6 Modules Inheritance Gems6 Modules Inheritance Gems
6 Modules Inheritance Gems
liahhansen
 
2 Slides Conditionals Iterators Blocks Hashes Arrays
2 Slides   Conditionals Iterators Blocks Hashes Arrays2 Slides   Conditionals Iterators Blocks Hashes Arrays
2 Slides Conditionals Iterators Blocks Hashes Arrays
liahhansen
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in Java
CIB Egypt
 

Destaque (11)

2014 09 30_t1_bioinformatics_wim_vancriekinge
2014 09 30_t1_bioinformatics_wim_vancriekinge2014 09 30_t1_bioinformatics_wim_vancriekinge
2014 09 30_t1_bioinformatics_wim_vancriekinge
 
Web Scraping
Web ScrapingWeb Scraping
Web Scraping
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013
 
1 Intro
1   Intro1   Intro
1 Intro
 
3 Strings Symbols
3 Strings Symbols3 Strings Symbols
3 Strings Symbols
 
6 Modules Inheritance Gems
6 Modules Inheritance Gems6 Modules Inheritance Gems
6 Modules Inheritance Gems
 
2 Slides Conditionals Iterators Blocks Hashes Arrays
2 Slides   Conditionals Iterators Blocks Hashes Arrays2 Slides   Conditionals Iterators Blocks Hashes Arrays
2 Slides Conditionals Iterators Blocks Hashes Arrays
 
5 Files Io
5 Files Io5 Files Io
5 Files Io
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in Java
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job? Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
 

Semelhante a 4 Regex Enumerables

PERL Unit 6 regular expression
PERL Unit 6 regular expressionPERL Unit 6 regular expression
PERL Unit 6 regular expression
Binsent Ribera
 
We9 Struts 2.0
We9 Struts 2.0We9 Struts 2.0
We9 Struts 2.0
wangjiaz
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
mussawir20
 
Php Calling Operators
Php Calling OperatorsPhp Calling Operators
Php Calling Operators
mussawir20
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Language
zone
 

Semelhante a 4 Regex Enumerables (20)

Ruby RegEx
Ruby RegExRuby RegEx
Ruby RegEx
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
PERL Unit 6 regular expression
PERL Unit 6 regular expressionPERL Unit 6 regular expression
PERL Unit 6 regular expression
 
Php2
Php2Php2
Php2
 
Prototype js
Prototype jsPrototype js
Prototype js
 
Form Validation
Form ValidationForm Validation
Form Validation
 
Ruby Enumerable
Ruby EnumerableRuby Enumerable
Ruby Enumerable
 
We9 Struts 2.0
We9 Struts 2.0We9 Struts 2.0
We9 Struts 2.0
 
JSP Custom Tags
JSP Custom TagsJSP Custom Tags
JSP Custom Tags
 
Changing Template Engine
Changing Template EngineChanging Template Engine
Changing Template Engine
 
Freebasing for Fun and Enhancement
Freebasing for Fun and EnhancementFreebasing for Fun and Enhancement
Freebasing for Fun and Enhancement
 
Combres
CombresCombres
Combres
 
XSD
XSDXSD
XSD
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
 
Php Calling Operators
Php Calling OperatorsPhp Calling Operators
Php Calling Operators
 
Array
ArrayArray
Array
 
[Erlang LT] Regexp Perl And Port
[Erlang LT] Regexp Perl And Port[Erlang LT] Regexp Perl And Port
[Erlang LT] Regexp Perl And Port
 
Erlang with Regexp Perl And Port
Erlang with Regexp Perl And PortErlang with Regexp Perl And Port
Erlang with Regexp Perl And Port
 
CGI With Object Oriented Perl
CGI With Object Oriented PerlCGI With Object Oriented Perl
CGI With Object Oriented Perl
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Language
 

Último

Último (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 

4 Regex Enumerables

  • 1. Class 4 Regular Expressions & Enumerables
  • 3. What are Regular Expressions Regular expressions allow matching and manipulation of textual data. Abbreviated as regex or regexp, or alternatively, just patterns
  • 4. What are Regular Expressions For? Scan a string for multiple occurrences of a pattern. Replace part of a string with another string. Split a string based on a matching separator.
  • 5.
  • 6.
  • 7. Regex Basics [abc] A single character: a, b or c [^abc] Any single character but a, b, or c [a-z] Any single character in the range a-z [a-zA-Z] Any single character in the range a-z or A-Z ^ Start of line $ End of line Start of string End of string
  • 8. Regex Basics cont... . Any single character Any whitespace character Any non-whitespace character Any digit Any non-digit Any word character (letter, number, underscore) Any non-word character Any word boundary character
  • 9. Regex Basics cont... (...) Capture everything enclosed (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
  • 10. 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
  • 11. 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
  • 12. Scan >> numbers = "one two three" => "one two three" >> numbers.scan(/+/) => ["one", "two", "three”]
  • 13. Split with Regular Expressions >> "one twothree".split(//) => ["one", ”two", "three"]
  • 15. gsub with a block "one twothree".gsub(/(+)/) do |w| puts w end one two three
  • 16. Title Case Capitalize All Words of a Sentence: >> full_name.gsub(//){|s| s.upcase} => "Yukihiro Matsumoto"
  • 17. Live Coding Example Scraping Thentic.com
  • 19. Why Use Enumerables Ruby's Enumerable module has methods for all kinds of tasks. If you can imagine a use for the #each method other than simply iterating, there is a good chance a method exists to do what you have in mind.
  • 20. What does Enumerable Mean? Collection objects (instances of Array, Hash, etc) typically “mixin” the Enumerable module The Enumerable module gives objects of collection classes additional collection-specific behaviors. The class requiring the Enumerable module must have an #each method because the additional collection-specific behaviors given by Enumerable are defined in terms of #each
  • 21. Mixing in Enumerable class MyCollection include Enumerable #lots of code def each #more code end end
  • 22. View all Classes Mixing in Enumerable ObjectSpace.each_object(Class) do |cl| puts cl if cl < Enumerable end
  • 23. Enumerable::Enumerator Struct::Tms Dir File IO Range Struct Hash Array String Struct::Group Struct::Passwd MyCollection StringIO Gem::SourceIndex YAML::Set YAML::Pairs YAML::Omap YAML::SpecialHas
  • 24. Test an Instance or Class >> a = [1,2,3] => [1, 2, 3] >> a.respond_to? :any? => true >> a.is_a? Enumerable => true >> Array < Enumerable => true
  • 25. each Classes that include the Enumerable module must have an #each method. The #each method yields items to a supplied code block, one at a time Different Classes define #each differently Array: #each yields each element Hash: each yields #each key/value pair as a two-element array >> v_names = %w(car truck bike) => ["car", "truck", "bike"] >> v_names.each do |vehicle| ?> puts vehicle >> end
  • 26. map The map method modifies each member according to instructions in a block and returns the modified collection of members. >> v_names.map { |v| v.upcase} => ["CAR", "TRUCK", "BIKE"]
  • 27. grep The grep method 'searches' for members using a regular expression. >> v_names.grep /a/ => ["car"] >> v_names.grep(/a/) { |v| v.upcase} => ["CAR"]
  • 28. find >> v_names.find { |v| v.size > 3} => "truck" >> v_names.find { |v| v.size > 2} => "car" >> v_names.find do |v| v.size > 3 && v.size < 5 end => "bike"
  • 29. all? The all? method returns true if all of the members of a collection satisfy the evaluation of the block. Otherwise it returns false. >> v_names.all? { |v| v.length > 2} => true >> v_names.all? { |v| v.length > 10} => false
  • 30. any? The any? method returns true if any of the members of a collection satisfy the evaluation of the block. Otherwise it returns false. >> v_names.any? { |v| v.length == 3} => true >> v_names.any? { |v| v = "car"} => true
  • 31. Working with Complex Data irb >> load 'vehicles.rb' => true
  • 32. inject >> $vehicles.inject(0) do |total_wheels, v| ?> total_wheels += v[:wheels] >> end => 10 >> $vehicles.inject([]) do |classes, v| ?> classes += v[:classes] >> end.uniq => [:ground, :water, :air]
  • 33. Complex Operations >> $vehicles.find do |v| ?> v[:name] =~ /Plane/ >> end[:name] => "Plane" >> $vehicles.find_all do |v| ?> v[:name] =~ /Plane/ >> end.collect { |v| v[:name] } => ["Plane", "Sea Plane"] >> $vehicles.find_all do |v| ?> v[:wheels] > 0 >> end.collect { |v| v[:name] } => ["Car", "Truck", "Bike"]
  • 34. Complex Operations Continued >> $vehicles.find_all do |v| ?> v[:classes].include? :ground >> end.collect { |v| v[:name] } => ["Car", "Truck", "Bike", "Sea Plane"] >> $vehicles.find_all do |v| ?> v[:classes].include? :air >> end.collect { |v| v[:name] } => ["Plane", "Helicopter", "Sea Plane"]
  • 35. Homework Chapters: 10.1 – 10.8 11.1 -11.8

Notas do Editor

  1. s finds spaces, tabs and new lines
  2. its fine to use is_a in irb..in code should use respond_to?