apply regex in swift

Regex can easily be applied in Swift with the help of the NSRegularExpression class. It allows us to create and use regular expressions to match patterns in strings.

Here is an example of how to use Regex in Swift:

main.swift
let text = "Hello, World!"

do {
    let regex = try NSRegularExpression(pattern: "\\w+")
    let range = NSRange(text.startIndex..<text.endIndex, in: text)
    let matches = regex.matches(in: text, range: range)
    
    for match in matches {
        let wordRange = Range(match.range, in: text)!
        let word = text[wordRange]
        print(word)
    }
} catch let error {
    print("Invalid regex: \(error.localizedDescription)")
}
440 chars
16 lines

In this example, we create a regular expression pattern that matches any word character (\\w+). We then create an NSRange object that encompasses the entire input string. Finally, we call matches(in:range:) on our NSRegularExpression object to find all matches in our input string, and we loop through the results to print out each word that was found.

Note that using try and a do-catch block is essential when working with NSRegularExpression, because the initializer and methods can throw errors if the provided regular expression is invalid.

This example only scratches the surface of what you can do with Regex in Swift, but it should give you a good starting point for using this powerful tool in your own projects.

gistlibby LogSnag