Code Snippet: Matching Regular Expressions

From Coder Merlin™

Get the first regex match in a string

Swift

import Foundation

let pearCountRegex = "(?<=There are )[0-9]+(?= pears)"
let pearString = "There are 587 pears"

if let range = pearString.range(of:pearCountRegex, options:.regularExpression) {
    // Prints 587
    print(pearString[range])
} else {
    print("No matches for pearCountRegex found in pearString")
}