1.8. Extracting Parts of a String That Match Patterns
Problem
You want to extract one or more parts of a string that match the regular-expression patterns you specify.
Solution
Define the regular-expression patterns you want to extract, placing parentheses around them so you can extract them as “regular-expression groups.” First, define the desired pattern:
valpattern="([0-9]+) ([A-Za-z]+)".r
Next, extract the regex groups from the target string:
val pattern(count, fruit) = "100 Bananas"
This code extracts the numeric field and the alphabetic field from
the given string as two separate variables, count and fruit, as shown in the Scala REPL:
scala>val pattern = "([0-9]+) ([A-Za-z]+)".rpattern: scala.util.matching.Regex = ([0-9]+) ([A-Za-z]+) scala>val pattern(count, fruit) = "100 Bananas"count: String = 100 fruit: String = Bananas
Discussion
The syntax shown here may feel a little unusual because it seems
like you’re defining pattern as a
val field twice, but this syntax is
more convenient and readable in a real-world example.
Imagine you’re writing the code for a search engine like Google, and you want to let people search for movies using a wide variety of phrases. To be really convenient, you’ll let them type any of these phrases to get a listing of movies near Boulder, Colorado:
"movies near 80301" "movies 80301" "80301 movies" "movie: 80301" "movies: 80301" "movies near boulder, co" "movies near boulder, colorado"
One way you can allow all these phrases to be used is to define a series ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access