find all words ending in lex in a string with regex in swift

You can use the following regular expression to find all the words ending in "lex" in a string:

main.swift
let inputString = "Alex and Max saw a duplex near the annex"
let pattern = "\\b\\w*lex\\b"
let regex = try! NSRegularExpression(pattern: pattern)

let matches = regex.matches(in: inputString, range: NSRange(inputString.startIndex..., in: inputString))
let words = matches.map { String(inputString[Range($0.range, in: inputString)!]) }

print(words) // ["Alex", "duplex", "annex"]
380 chars
9 lines

In the above code, we define a string inputString and a regular expression pattern that matches any word that ends with "lex" using the word boundary character \b, zero or more word characters \w*, the characters "lex" literally, and another word boundary character \b.

We then create an instance of NSRegularExpression with the created pattern, and use the matches(in:range:) method to find all matches in the input string. Finally, we extract the matched words from the input string using the Range method and store them in an array words.

gistlibby LogSnag