find all words ending in lex in a string in swift

You can use regular expressions to find all the words ending in "lex" in a given string using the following code in Swift:

main.swift
let inputString = "alex perplex flex feeds"
let pattern = "\\w*lex\\b"

if let regex = try? NSRegularExpression(pattern: pattern) {
    let results = regex.matches(in: inputString, range: NSRange(inputString.startIndex..., in: inputString))
    let words = results.map {
        String(inputString[Range($0.range, in: inputString)!])
    }
    print(words) // ["alex", "perplex", "flex"]
}
390 chars
11 lines

Here, we're using NSRegularExpression to create a regular expression pattern that looks for one or more word characters (\\w*) followed by "lex" and a word boundary (\\b).

We then apply this pattern to the inputString using the matches(in:range:) method to get an array of NSTextCheckingResult instances representing the matches.

We then extract the corresponding substrings from the inputString using the Range(_:in:) and String(_:) initializers, and store them in an array words. Finally, we print out the array words.

gistlibby LogSnag