【发布时间】:2016-03-04 04:21:25
【问题描述】:
我有一个 UITextField,用户可以在其中编写描述。
示例:“这是我的#car 的图像。酷炫的#sunshine 背景也适合我的#fans。”
如何检测标签“汽车”、“阳光”和“粉丝”,并将它们添加到数组中?
【问题讨论】:
-
@BartłomiejSemańczyk - 是的,我忘记了,但你仍然明白我的意思吗?
我有一个 UITextField,用户可以在其中编写描述。
示例:“这是我的#car 的图像。酷炫的#sunshine 背景也适合我的#fans。”
如何检测标签“汽车”、“阳光”和“粉丝”,并将它们添加到数组中?
【问题讨论】:
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
【讨论】:
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]
【讨论】:
检查这个 pod:https://cocoapods.org/pods/twitter-text
在TwitterText类中有一个方法(NSArray *)hashtagsInText:(NSString *)text checkingURLOverlap (BOOL)checkingURLOverlap
Twitter 创建了这个 pod 来查找 #、@、URL,所以在我看来,没有更好的方法可以做到这一点。 :)
【讨论】:
@Anurag 答案的 Swift 3 版本:
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))
})
}
}
【讨论】: