Swift Regular Expressions - kgleong/software-engineering GitHub Wiki

Regular Expresssions in Swift

Capturing Groups

for term in searchBarText.components(separatedBy: " ") {
    do {
        // search for `user:<username>` syntax
        let regex = try NSRegularExpression(
            pattern: "^user:([^\\s]+)$",
            options: [NSRegularExpression.Options.caseInsensitive]
        )

        let results = regex.matches(
            in: term,
            options: [],
            range: NSRange(location: 0, length: term.characters.count)
        )

        if results.isEmpty {
            // No match found
            searchTerms.append(term)
        }
        else {
            // Convert String to an NSString, which is compatible with
            // the NSRange object that the regex result contains.
            let termString = term as NSString

            for result in results {
                // add the first capturing group, which is the username.
                // 0 is the matching string, 1 is the first capturing group
                let userName = termString.substring(with: result.rangeAt(1))
                usersSearch.append(userName)
            }
        }
    }
    catch {
        print("NSRegularExpression error: \(error)")
    }
}
⚠️ **GitHub.com Fallback** ⚠️