-
Notifications
You must be signed in to change notification settings - Fork 3
Swift Regular Expressions
Kevin Leong edited this page Nov 21, 2016
·
1 revision
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)")
}
}