Introduction
We use scanning to find all parts of a text that match a pattern. It helps us pick out many pieces at once.
We use scanning to find all parts of a text that match a pattern. It helps us pick out many pieces at once.
string.scan(pattern) # returns an array of all matchespattern can be a string or a regular expression.
The result is an array with all matching parts found in the string.
"hello 123 world 456".scan(/\d+/)"apple banana cherry".scan(/\b\w{6}\b/)
"one two three".scan("o")
This program finds all email addresses in the text and prints them one by one.
text = "My emails are test1@example.com and test2@example.org" matches = text.scan(/\w+@\w+\.\w+/) puts "Found emails:" matches.each { |email| puts email }
If no matches are found, scan returns an empty array.
You can use parentheses in your pattern to capture parts of the match.
scan finds all matches of a pattern in a string.
It returns an array with all matching parts.
Use regular expressions to find complex patterns easily.
scan do when used on a string?scanscan method searches the string for all occurrences of a pattern.scanscan returns matches array [OK]str using scan?/pattern/ to denote regular expressions.\d+ matches one or more digits. The pattern must be inside slashes for regex.text = "cat bat rat" matches = text.scan(/.at/) puts matches.inspect
/.at/. matches any single character, so .at matches any three-letter word ending with 'at'.scan on the stringsentence. What is the error?
sentence = "apple banana apricot avocado"
words = sentence.scan("a\w+")
puts words.inspectscanscan method expects a regex pattern, not a plain string./a\w+/ to match words starting with 'a'.data = "log12 ID123, ID456, ID789", how can you use scan to extract only the numeric parts after each 'ID' (e.g., ["123", "456", "789"])?/ID(\d+)/ matches 'ID' followed by digits, capturing only digits in parentheses. This ignores other digits like '12' in 'log12'.scan and flatten the resultscan returns an array of arrays for capture groups, so flatten converts it to a simple array of strings.Pass the test and this pattern moves unknown