Capstone: extracting prices
Everything so far finds one match. Add the g (global) flag and
str.match(regex) changes behavior: instead of an array with capture-group
details, it returns every match found in the string, in order - or null if
there are none.
This is the shape of real text-extraction work: a messy paragraph, a pattern
for the piece you want, and a loop-free way to pull out every occurrence.
Your task: write extractPrices(text), returning an array of every dollar
amount found in text (like "$4" or "$19.99"), in the order they appear.
Return an empty array if none are found. A price is a $ followed by one or
more digits, optionally followed by a decimal point and exactly two digits.
You'll practice:
Finding every match with the g flag
Handling match()'s null result when nothing matches
Combining \$, \d+, and an optional group into one pattern
Show a hint
Show solution
Related reading: Using Regex for Real (and the Gotchas) →
Previous Next