Text Processing
Gsub Scan
gsub replaces matching text, while scan collects matches.
scan
`scan` returns all non-overlapping matches from a string.
Gsub Scan
gsub_scan.rb
Replay: real traced execution (multi-file project)
word = "red"
text = "red blue red"
pattern = Regexp.new(word)
matches = text.scan(pattern)
replaced = text.gsub(pattern, "item")
puts "word=#{word}"
puts "matches=#{matches.length}"
puts "replaced=#{replaced}"
word = "blue"
text = "red blue red"
pattern = Regexp.new(word)
matches = text.scan(pattern)
replaced = text.gsub(pattern, "item")
puts "word=#{word}"
puts "matches=#{matches.length}"
puts "replaced=#{replaced}"
word = "green"
text = "red blue red"
pattern = Regexp.new(word)
matches = text.scan(pattern)
replaced = text.gsub(pattern, "item")
puts "word=#{word}"
puts "matches=#{matches.length}"
puts "replaced=#{replaced}"
word ← red, text ← red blue red, pattern ← (?-mix:red), matches ← ["red", "red"]
1word→ red = "red" #@word="blue", "green"2text→ red blue red = "red blue red"3pattern→ (?-mix:red) = Regexp.new(wordred)45matches→ ["red", "red"] = text.scan(pattern)["red", "red"]6replaced→ item blue item = text.gsub(pattern, "item")item blue item78puts "word=#{wordred}"9puts "matches=#{matches.length2}"10puts "replaced=#{replaceditem blue item}"outputword=red matches=2 replaced=item blue item
word ← blue, text ← red blue red, pattern ← (?-mix:blue), matches ← ["blue"]
1word→ blue = "blue"2text→ red blue red = "red blue red"3pattern→ (?-mix:blue) = Regexp.new(wordblue)45matches→ ["blue"] = text.scan(pattern)["blue"]6replaced→ red item red = text.gsub(pattern, "item")red item red78puts "word=#{wordblue}"9puts "matches=#{matches.length1}"10puts "replaced=#{replacedred item red}"outputword=blue matches=1 replaced=red item red
word ← green, text ← red blue red, pattern ← (?-mix:green), matches ← []
1word→ green = "green"2text→ red blue red = "red blue red"3pattern→ (?-mix:green) = Regexp.new(wordgreen)45matches→ [] = text.scan(pattern)[]6replaced→ red blue red = text.gsub(pattern, "item")red blue red78puts "word=#{wordgreen}"9puts "matches=#{matches.length0}"10puts "replaced=#{replacedred blue red}"outputword=green matches=0 replaced=red blue red