Swift Regular Expressions - kgleong/software-engineering GitHub Wiki
Regular Expresssions in Swift
Capturing Groups
fortermin searchBarText.components(separatedBy:""){do{
// search for `user:<username>` syntax
letregex=tryNSRegularExpression(
pattern:"^user:([^\\s]+)$",
options:[NSRegularExpression.Options.caseInsensitive])letresults= 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.
lettermString= term asNSStringforresultin results {
// add the first capturing group, which is the username.
// 0 is the matching string, 1 is the first capturing group
letuserName= termString.substring(with: result.rangeAt(1))
usersSearch.append(userName)}}}catch{print("NSRegularExpression error: \(error)")}}