Swift Regular Expressions - kgleong/software-engineering GitHub Wiki
Regular Expresssions in Swift
Capturing Groups
forterminsearchBarText.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))ifresults.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=termasNSStringforresultinresults{
// 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)")}}