Code Snippet: Matching Regular Expressions

From Coder Merlin
Jump to navigation Jump to search

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


Designed with pride in Silicon Valley, CA, USA