Reputation: 25
I have a UITextField where the users can write a description.
Example: "This is a image of my #car. A cool #sunshine background also for my #fans."
How can i detect the hashtags "car", "sunshine" and "fans", and add them to a array?
Upvotes: 1
Views: 1630
Reputation: 999
Swift 4.2 version. At the end we return a list of hashtags/keywords without #
.
extension String {
func getHashtags() -> [String]? {
let hashtagDetector = try? NSRegularExpression(pattern: "#(\\w+)", options: NSRegularExpression.Options.caseInsensitive)
let results = hashtagDetector?.matches(in: self, options: .withoutAnchoringBounds, range: NSRange(location: 0, length: count))
return results?.map({
(self as NSString).substring(with: $0.range(at: 1)).capitalized
})
}
}
e.g
Input
#hashtag1 #hashtag2 #hashtag3 #hashtag4 #hashtag5
Output
[hashtag1, hashtag2, hashtag3, hashtag4, hashtag5]
Upvotes: 1
Reputation: 569
Swift 3 version of @Anurag's answer:
extension String {
func getHashtags() -> [String]? {
let hashtagDetector = try? NSRegularExpression(pattern: "#(\\w+)", options: NSRegularExpression.Options.caseInsensitive)
let results = hashtagDetector?.matches(in: self, options: NSRegularExpression.MatchingOptions.withoutAnchoringBounds, range: NSMakeRange(0, self.characters.count)).map { $0 }
return results?.map({
(self as NSString).substring(with: $0.rangeAt(1))
})
}
}
Upvotes: 0
Reputation: 4994
Check this pod: https://cocoapods.org/pods/twitter-text
In TwitterText
class there is a method (NSArray *)hashtagsInText:(NSString *)text checkingURLOverlap (BOOL)checkingURLOverlap
Twitter created this pod for finding #, @, URLs so in my opinion there is no better way to do this. :)
Upvotes: 0
Reputation: 675
let frame = CGRect(x: 0.0, y: 0.0, width: 100.0, height: 30.0)
let description = UITextField(frame: frame)
description.text = "This is a image of my #car. A cool #sunshine background also for my #fans."
extension String {
func getHashtags() -> [String]? {
let hashtagDetector = try? NSRegularExpression(pattern: "#(\\w+)", options: NSRegularExpressionOptions.CaseInsensitive)
let results = hashtagDetector?.matchesInString(self, options: NSMatchingOptions.WithoutAnchoringBounds, range: NSMakeRange(0, self.utf16.count)).map { $0 }
return results?.map({
(self as NSString).substringWithRange($0.rangeAtIndex(1))
})
}
}
description.text?.getHashtags() // returns array of hashtags
Source: https://github.com/JamalK/Swift-String-Tools/blob/master/StringExtensions.swift
Upvotes: 3