CS 330 Lecture 7 – Regex: Replacement with Blocks
Agenda
- what ?s
- program this
- gsub examples
- src2html
- eval’ing embedded math
- regex bingo
TODO
Right now:
- You and a partner make a 4×4 grid of randomly generated strings. Include upper- and lowercase letters, numbers, whitespace, and punctuation. Keep the strings short. There’s no free space.
Before Wednesday:
- Familiarize yourself with grammars and ANTLR. Read Grammar: The Language of Languages. On a 1/4 sheet, write a little grammar to match boolean expressions comprised of boolean literals, variable identifiers, binary operators
||
and&&
, and unary operator!
. Allow for parentheses to elevate the enclosed operation’s precedence:!(true || isTall)
.
Note
Let’s start with a Program This, excerpted from Advent of Code:
Santa needs help figuring out which strings in his text file are naughty or nice.
A nice string is one with all of the following properties:
- It contains at least three vowels (
aeiou
only), likeaei
,xazegov
, oraeiouaeiouaeiou
.- It contains at least one letter that appears twice in a row, like
xx
,abcdde
(dd
), oraabbccdd
(aa
,bb
,cc
, ordd
).- It does not contain the strings
ab
,cd
,pq
, orxy
, even if they are part of one of the other requirements.
With a partner, write a write Ruby expression that evaluates true if a string is nice.
Today we close out our focus on regular expressions with a few more examples, hitting upon the ideas of greedy vs. lazy and replacing the matching text with the result of some code using a block.
Code
advent.rb
/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 `'
eval_report.rb
/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 `'