Code Snippet: Matching Regular Expressions

From Coder Merlin
Revision as of 18:27, 25 January 2020 by Yarsenius (talk | contribs) (Created page with "= Get the first regex match in a string = == Swift == <syntaxhighlight lang="swift"> import Foundation let pearCountRegex = "(?<=There are )[0-9]+(?= pears)" let pearString...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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")
}