170 likes | 329 Views
Regular Expressions using Ruby. Assignment: Midterm Class: CPSC5135U – Programming Languages Teacher: Dr. Woolbright Student: James Bowman. Regular Expression Definition.
E N D
Regular Expressions using Ruby Assignment: Midterm Class: CPSC5135U – Programming Languages Teacher: Dr. Woolbright Student: James Bowman
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”).
Regular Expression Examples Character classes:
Regular Expression Examples Special Character Classes:
Regular Expression Examples Alternatives:
Regular Expression Examples Anchors:
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.
Regexp Class • Escape: • Escapes any characters that would have special meaning in a regular expression. Example: Regexp.escape('\*?{}.') #=> \\\*\?\{\}\.
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+/
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
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
Code Examples Please See Attached Code for more examples