Patterns in text: regular expressions
With include? you find a word you know exactly. Often, though, you only know what something looks like: “a number”, “a time”, “a word starting with S”. That is what regular expressions (regex for short) are for: patterns between two slashes. match? asks whether the pattern fits anywhere in the text:
sentence = "Chunky eats 3 strips of bacon"
p sentence.include?("bacon")
p sentence.match?(/bacon/)
sentence.match?(/\d/)/bacon/ matches exactly that word – nothing new so far. It gets interesting with the placeholders: \d stands for a digit, \w for a word character (letter, digit or _), \s for whitespace and . for any character. A quantifier after it says how often: + means “one or more”, * “any number, even none”, ? “none or one”, {2} “exactly two”. scan collects every match in an array:
diary = "Mon: 3 strips, Tue: 12 strips, Wed: 7 strips"
p diary.scan(/\d/)
diary.scan(/\d+/)See the difference? /\d/ finds every digit on its own, /\d+/ joins neighbouring digits into one number. The matches are strings. Lesson 13 was about transforming lists – that is how you turn them into numbers and go on calculating:
diary.scan(/\d+/).map(&:to_i).sumSquare brackets form a character class: [aeiou] matches a vowel, [A-Z] a capital letter, [^0-9] anything but a digit. A ^ at the front anchors the pattern to the start of the line, $ to its end. And an i after the closing slash makes the search ignore case:
words = ["Bacon", "Egg", "Coffee", "bacon", "Bread"]
p words.select { |word| word.match?(/bacon/i) }
p words.select { |word| word.match?(/^[A-C]/) }
"Chunky Bacon".scan(/[aeiou]/).lengthOften you want to know not just whether something matches, but what. match returns a MatchData object. Round brackets form groups, and with (?<name>…) you give a group a name to fetch it by. If nothing matches, you get nil – handy for if. For a single match there is an even shorter way: text[/pattern/] returns the first match or nil:
line = "Chunky: 3 strips at 07:45"
found = line.match(/(?<who>\w+): (?<count>\d+)/)
p found[:who]
p found[:count].to_i
p line[/\d\d:\d\d/]
p "No number here".match(/\d+/)For replacing there are sub (the first match) and gsub (all of them): instead of a fixed word, they take a pattern. That is how you tidy up stray spaces, for instance:
text = "Bacon, eggs,toast , coffee"
p text.gsub(/\s*,\s*/, " | ")
text.gsub(/[aeiou]/, "*")At first sight, regular expressions look as if a cat had walked across the keyboard. The trick: build them piece by piece and test each piece with match? or scan, until the pattern finds everything it should – and nothing else. The most important characters are on the . In the advanced course, lesson 106 (parsing text), a regex with named groups takes apart the lines of a time tracker.
times – every time of day from all the notes, as strings like "07:45" (with scan) – and bacon_days – how many notes mention bacon, in capitals or not (with count and match?). Expected are ["07:45", "10:15", "12:30"] and 2.notes = [
"Breakfast at 07:45: Bacon",
"Snack at 10:15: apple",
"Lunch at 12:30: bacon and egg",
"Evening: not hungry"
]
# times = ... # every time of day, e.g. "07:45"
# bacon_days = ... # how many notes mention bacon (capitals or not)
scan returns an array of the groups for every match. Take the pairs pairs out of report with a pattern of two groups – name, colon, space, number: [["Chunky", "3"], ["Kaz", "12"], ["Isi", "7"]]. Then add the numbers up in total: 22.report = "Chunky: 3 strips, Kaz: 12 strips, Isi: 7 strips"
# pairs = ... # [["Chunky", "3"], ["Kaz", "12"], ["Isi", "7"]]
# total = ... # the numbers added up: 22