CS 330 Lecture 6 – Regex: Capturing and Substituting
Agenda
- what ?s
- what is a regex?
- capturing
- substituting
TODO
- For an extra credit quarter sheet, do these two things:
- Get at least 1000 points at Regex Golf. Don’t look up the answers anywhere. Start a post on Piazza sharing your solutions.
- Create your own level by clicking on the Help button in the navigation bar. Share the link (but not solutions) in the same Piazza post. Try out some other students’ levels and post your solutions in a followup to their note!
Note
Under the hood, our regular expressions are converted into something called a state machine. This idea is pervasive enough in our field that we should consider a few examples of state machines. Here’s one from Nystrom’s Game Programming Patterns:
Let’s do a few with regex:
- All strings that start with a capital letter followed by a lowercase letter
- Strings comprised only of 0s and 1s, alternating. For example 010, 1, 01, 101010.
- a time of day
Next we’ll visit some more examples of using regex for these problems:
- first column
- period-should-be-spaces between words
- evaluate embedded math
- repeated words
- Advent of Code, day 5
- src2html
Code
firstcol
/usr/lib/ruby/2.7.0/rubygems/dependency.rb:311:in `to_specs': Could not find 'coderay' (>= 0) among 56 total gem(s) (Gem::MissingSpecError) Checked in 'GEM_PATH=/.gem/ruby/2.7.0:/var/lib/gems/2.7.0:/usr/lib/ruby/gems/2.7.0:/usr/share/rubygems-integration/2.7.0:/usr/share/rubygems-integration/all:/usr/lib/x86_64-linux-gnu/rubygems-integration/2.7.0:/home/johnch/.gems', execute `gem env` for more information from /usr/lib/ruby/2.7.0/rubygems/dependency.rb:323:in `to_spec' from /usr/lib/ruby/2.7.0/rubygems/core_ext/kernel_gem.rb:62:in `gem' from ./coderay:24:in `'
fixperiods
/usr/lib/ruby/2.7.0/rubygems/dependency.rb:311:in `to_specs': Could not find 'coderay' (>= 0) among 56 total gem(s) (Gem::MissingSpecError) Checked in 'GEM_PATH=/.gem/ruby/2.7.0:/var/lib/gems/2.7.0:/usr/lib/ruby/gems/2.7.0:/usr/share/rubygems-integration/2.7.0:/usr/share/rubygems-integration/all:/usr/lib/x86_64-linux-gnu/rubygems-integration/2.7.0:/home/johnch/.gems', execute `gem env` for more information from /usr/lib/ruby/2.7.0/rubygems/dependency.rb:323:in `to_spec' from /usr/lib/ruby/2.7.0/rubygems/core_ext/kernel_gem.rb:62:in `gem' from ./coderay:24:in `'