CS 330 Lecture 7 – Regex Cont’d
February 9, 2015 by Chris Johnson. Filed under cs330, lectures, spring 2015.
Agenda
- what ?s
- what does this do?
- substitution
- capturing
- lookaround assertions
TODO
- 1/4 sheet: Try your hand at Regex Golf. Report some of your regices and your score.
What Does This Do?
#!/usr/bin/env ruby
Dir.glob('*.html?').each do |f|
File.delete(f)
end
show
#!/usr/bin/env ruby
text = IO.read(ARGV[0]);
text.scan(/a\s*[aeiou]/) do |match|
puts match
end
show
#!/usr/bin/env ruby
text = IO.read(ARGV[0])
puts text.scan(/"[^"]*"/)
show
#!/usr/bin/env ruby
puts IO.read(ARGV[0]).scan(/\bcos\b)
show
Code
arithmetic.txt
Day 1: the number of bunnies was {{ 5 }}.
Day 2: the number of bunnies was {{ 5 * 2 }}.
Day 3: the number of bunnies was {{ 5 ** 40 }}.
calc.rb
#!/usr/bin/env ruby
raw = IO.read(ARGV[0])
cooked = raw.gsub(/\{\{(.*?)\}\}/) do |match|
# puts match
# puts $1
eval($1)
end
puts cooked
music.rb
#!/usr/bin/env ruby
notes = "A B C C# Db A B G Ab Bb C# Db G#"
cooked = notes.gsub(/A(?!b|#)/, 'G')
puts notes
puts cooked
Haiku
Tool manifesto
Help eager folks enjoy work
Neuter all the rest
show