Regex type
With the Regex type we can search for a pattern in a string and then use methods like contains(:), firstMatch(of:) or matches(of:) in order to find matches. We can also use instances of the Regex type with the string matches() method that we saw in the previous section. Let’s look at how we can use the Regex type, starting with the string methods.
To see how we can use the Regex type with our String methods, we will use the same example that we used in the previous section, however rather than creating a regular expression literal, we will create an instance of the Regex type. Here is the code:
let pattern = Regex(/\b\w+\b/)
text = "Hello from regex literal"
let matches = text.matches(of: pattern)
for match in matches {
print("-- \(text[match.range])")
}
This code begins by creating an instance of the Regex type using the pattern /\b\w+\b/ which will match each word in a string. We use the matches() method of the String to return an array of...