检测主题标签并添加到数组

时间:2015-11-30 13:50:06

标签: ios swift hashtag

我有一个UITextField,用户可以在其中编写说明。

示例:"这是我的#car的图像。我的#fans也很酷#sunshine背景。"

我如何检测标签" car"," sunshine"和"粉丝",并将它们添加到数组?

4 个答案:

答案 0 :(得分:3)

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

来源:https://github.com/JamalK/Swift-String-Tools/blob/master/StringExtensions.swift

答案 1 :(得分:1)

Swift 4.2版本。最后,我们返回不含#的#标签/关键字列表。

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

}

例如

输入 #hashtag1 #hashtag2 #hashtag3 #hashtag4 #hashtag5

输出 [hashtag1, hashtag2, hashtag3, hashtag4, hashtag5]

答案 2 :(得分:0)

选中此广告连结:https://cocoapods.org/pods/twitter-text

TwitterText课程中,有一种方法(NSArray *)hashtagsInText:(NSString *)text checkingURLOverlap (BOOL)checkingURLOverlap

Twitter创建了这个用于查找#,@,URL的pod,所以在我看来没有更好的方法可以做到这一点。 :)

答案 3 :(得分:0)

Swift 3版@Anurag的答案:

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

}