use regex to find all words ending with "lex" in swift

You can use the NSRegularExpression class in Swift to find all words ending with "lex" in a string. Here's an example code snippet:

main.swift
let input = "Alex likes to flex his muscles."
let pattern = "\\b\\w+lex\\b"

do {
  let regex = try NSRegularExpression(pattern: pattern)
  let matches = regex.matches(in: input, range: NSRange(input.startIndex..., in: input))
  
  for match in matches {
    let wordRange = match.range
    if let range = Range(wordRange, in: input) {
      let word = input[range]
      print(word)
    }
  }
} catch {
  print("Regex failed: \(error.localizedDescription)")
}
461 chars
18 lines

In this example, we first define our input string and the pattern that we want to match. The pattern is "\b\w+lex\b", which matches any word that ends with "lex".

Next, we create an instance of NSRegularExpression and use it to find all matches in the input string. We loop through each match and extract the corresponding word using the range property of the match.

Finally, we print out each word that matches the pattern. The output of this code snippet will be:

main.swift
flex
5 chars
2 lines

since that is the only word in the input string that ends with "lex".

gistlibby LogSnag