A Scala substring example: I ran into a situation today where I wanted to get a string after the Nth occurrence of another string, in this case after the 6th occurrence of a “:” character. There are probably many ways to determine the Nth occurrence of a string in another string, but as a quick example, this is what I did.
First, I started with this string:
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 1.9, “Extracting Parts of a String that Match Patterns.”
You want to extract one or more parts of a Scala
String that match the regular-expression patterns you specify.
Define the regular-expression (regex) patterns you want to extract, placing parentheses around them so you can extract them as “regular-expression groups.” First, define the desired pattern:
This is a little Perl script I wrote to parse a CSV file I periodically download from Google AdSense. It does the following things:
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 10.21, “How to Extract Unique Elements from a Scala Sequence”
You have a collection that contains duplicate elements, and you want to remove the duplicates.
distinct method on the collection:
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 10.18, “How to Extract a Sequence of Elements from a Scala Collection”
You want to extract a sequence of contiguous elements from a collection, either by specifying a starting position and length, or a function.
Scala String FAQ: How can I extract one or more parts of a string that match the regular-expression patterns I specify?
Define the regular-expression patterns you want to extract from your
String, placing parentheses around them so you can extract them as “regular-expression groups.” First, define the desired pattern:
val pattern = "([0-9]+) ([A-Za-z]+)".r
Next, extract the regex groups from the target string:
Problem: Your XML data has an array of elements, and you need to extract the first element, second element, or more generally, the Nth element, using Scala.
The following simplified version of the XML from the Yahoo Weather API has three
Problem: In a Scala application, you want to extract information from XML you receive, so you can use the data in your application.
Use the methods of the Scala
NodeSeq classes to extract the data. The most commonly used methods of the
Elem class are shown here: