extract

How to extract a substring near the Nth occurrence of a string or character in a string

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:

Scala: How to extract parts of a String that match regex patterns alvin July 10, 2017 - 8:32am

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.”

Problem

You want to extract one or more parts of a Scala String that match the regular-expression patterns you specify.

Solution

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:

How to extract unique elements from a Scala sequence

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”

Problem

You have a collection that contains duplicate elements, and you want to remove the duplicates.

Solution

Call the distinct method on the collection:

How to extract a sequence of elements from a Scala 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”

Problem

You want to extract a sequence of contiguous elements from a collection, either by specifying a starting position and length, or a function.

Scala: How to extract parts of a string that match a regex alvin May 30, 2015 - 5:10pm

Scala String FAQ: How can I extract one or more parts of a string that match the regular-expression patterns I specify?

Solution

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:

Scala: Extracting data from an array of XML elements

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.

Solution

The following simplified version of the XML from the Yahoo Weather API has three <forecast> elements:

How to extract data from XML nodes in Scala

Problem: In a Scala application, you want to extract information from XML you receive, so you can use the data in your application.

Solution

Use the methods of the Scala Elem and NodeSeq classes to extract the data. The most commonly used methods of the Elem class are shown here: