我有这个扩展名:
extension String {
public func seperateHashtags(char : String) -> [String]{
var word : String = ""
var words : [String] = [String]()
for chararacter in self.characters {
if String(chararacter) == char && word != "" {
words.append(word)
word = char
}else {
word += String(chararacter)
}
}
words.append(word)
return words
}
}
我想从任何给定的文本中获取一组主题标签。
我有UITextView
,其中包含文字:
write anything here... #one #two three #four
我希望有一个输出:
["one", "two", "four"]
但是当我这样做时:
print(myTextView.text.seperateHashtags("#"))
我得到了:
["write anything here... ", "#one ", "#two three ", "#four"]
我该如何解决?
答案 0 :(得分:5)
您可以使用正则表达式并以这种方式获取所有标签:
var hashtags = [String]()
var str = "#one #two three #four"
let regex = try NSRegularExpression(pattern: "(#[A-Za-z0-9]*)", options: [])
let matches = regex.matchesInString(str, options:[], range:NSMakeRange(0, str.characters.count))
for match in matches {
print("match = \(match.range)")
hashtags.append(NSString(string: str).substringWithRange(NSRange(location:match.range.location + 1, length:match.range.length - 1)))
}
<强>输出:强>
["one", "two", "four"]
答案 1 :(得分:0)
write anything here...
你不应该把它作为UITextField的占位符吗?