1 / 16

Regular Expressions using Ruby

Regular Expressions using Ruby. Assignment: Midterm Class: CPSC5135U – Programming Languages Teacher: Dr. Woolbright Student: James Bowman. Regular Expression Definition.

flann
Download Presentation

Regular Expressions using Ruby

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Regular Expressions using Ruby Assignment: Midterm Class: CPSC5135U – Programming Languages Teacher: Dr. Woolbright Student: James Bowman

  2. Regular Expression Definition • Regular Expressions provides a concise and flexible means for matching strings of text, such as particular characters, words, or patterns of characters. • Examples: Social Security Number(XXX-XX-XXXX), Telephone number(XXX-XXX-XXXX), or phrases to check for(“Cat Name: XXXX”).

  3. Regular Expression Modifiers

  4. Regular Expression Patterns

  5. Regular Expression Patterns Cont…

  6. Regular Expression Patterns Cont…

  7. Regular Expression Examples Character classes:

  8. Regular Expression Examples Special Character Classes:

  9. Regular Expression Examples Alternatives:

  10. Regular Expression Examples Anchors:

  11. Regexp Class • A Regexp holds a regular expression, used to match a pattern against strings. Regexps are created using the /…/ and %r{…} literals, and by the Regexp::new constructor.

  12. Regexp Class • Escape: • Escapes any characters that would have special meaning in a regular expression. Example: Regexp.escape('\*?{}.') #=> \\\*\?\{\}\.

  13. Regexp Class • New: • Constructs a new regular expression from pattern, which can be a string. Example: r1 = Regexp.new('^a-z+:\\s+\w+') #=> /^a-z+:\s+\w+/

  14. Search and Replace Example #!/usr/bin/ruby phone = "2004-959-559 #This is Phone Number" # Delete Ruby-style comments phone = phone.sub!(/#.*$/, "") puts "Phone Num : #{phone}" # Remove anything other than digits phone = phone.gsub!(/\D/, "") puts "Phone Num : #{phone}" Result: Phone Num : 2004-959-559 Phone Num : 2004959559

  15. Code Example – Matching on Strings #!/usr/bin/ruby line1 = “People are smarter than dogs"; line2 = "Dogs also like cats"; if ( line1 =~ /People(.*)/ ) puts "Line1 starts with People" end if ( line2 =~ /People(.*)/ ) puts "Line2 starts with Dogs" end Result: Line1 starts with People

  16. Code Examples Please See Attached Code for more examples

More Related