简体   繁体   中英

Detect hashtags and add to array

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?

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

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
    })
}

}

eg

Input #hashtag1 #hashtag2 #hashtag3 #hashtag4 #hashtag5

Output [hashtag1, hashtag2, hashtag3, hashtag4, hashtag5]

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. :)

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))
    })
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM