Code Snippet: Matching Regular Expressions

From Coder Merlin
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

Get the first regex match in a string[edit]

Swift[edit]

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")
}