Code Snippet: Matching Regular Expressions

From Coder Merlin
Jump to navigation Jump to search

Get the first regex match in a string[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
} else {
    print("No matches for pearCountRegex found in pearString")

CoderMerlin™ proudly recommends:

Your purchase via these links helps keep  Coder Merlin™ 's orbuculum ablaze. As an Amazon Associate we earn from qualifying purchases. Thank you for your support!

Designed with pride in Silicon Valley, CA, USA