gpt4 book ai didi

快速从文本中提取主题标签字符串

转载 作者:行者123 更新时间:2023-11-28 09:39:58 25 4
gpt4 key购买 nike

如何在 Swift 中从文本中提取主题标签字符串?我看到了一些答案,但它们对于我需要的东西来说似乎太复杂了,而且我真的不明白 RegEx 是如何工作的?

例如

文本:“这是#something,有很多#random #hashtags #123yay。”

我想要的是:“某物”、“随机”、“主题标签”、“123yay”。

谢谢!

最佳答案

这是将字符串转换为哈希检测字符串的辅助方法

此扩展从 sting 中找到 # 个单词,还包括阿拉伯语单词。

extension String {
func findMentionText() -> [String] {
var arr_hasStrings:[String] = []
let regex = try? NSRegularExpression(pattern: "(#[a-zA-Z0-9_\\p{Arabic}\\p{N}]*)", options: [])
if let matches = regex?.matches(in: self, options:[], range:NSMakeRange(0, self.count)) {
for match in matches {
arr_hasStrings.append(NSString(string: self).substring(with: NSRange(location:match.range.location, length: match.range.length )))
}
}
return arr_hasStrings
}
}

下面的方法将您的字符串转换为 Reach 彩色哈希字符串。

func convert(_ hashElements:[String], string: String) -> NSAttributedString {

let hasAttribute = [NSAttributedStringKey.foregroundColor: UIColor.orange]

let normalAttribute = [NSAttributedStringKey.foregroundColor: UIColor.black]

let mainAttributedString = NSMutableAttributedString(string: string, attributes: normalAttribute)

let txtViewReviewText = string as NSString

hashElements.forEach { if string.contains($0) {
mainAttributedString.addAttributes(hasAttribute, range: txtViewReviewText.range(of: $0))
}
}
return mainAttributedString
}

let text = "#Jaydeep #Viral you have to come for party"

let hashString = convert(text.findMentionText(), string: text)

输出:

enter image description here

关于快速从文本中提取主题标签字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51494476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com