繁体   English   中英

使用正则表达式更改句子中的单词颜色

[英]Change word colour from sentence with regex

我有一句话“这是我的第一次测试”,我需要将例如单词“first”更改为另一种颜色。 但是这个句子将来自后端。 所以,我可能需要用正则表达式从句子中提取单词,然后用另一种颜色支持它。 如何将这个词转换成句子,或者更好的方法来改变句子中单词的颜色?

     var string = "This is my text=\"first\" test!"
        let pattern = ".*(?=( - text=\"[\\w\\s]+\"))|(?<=text=\")([\\w\\s]+)"

        do {
            let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
            let matches = regex.matches(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count))
            for match in matches {
                if let range = Range(match.range, in: string) {
                    let name = string[range]
                    if let range = string.range(of: "text=\"\(name)\"") {
                        string.removeSubrange(range)
                        debugPrint("WORD CHANGE COLOR: \(name)") // first
                        debugPrint("PHRASE IS: \(string)") // This is my test!
                    }
                    let attrs1 = [NSAttributedString.Key.font :  UIFont.systemFont(ofSize: 20), NSAttributedString.Key.foregroundColor : UIColor.green]
                    let attrs2 = [NSAttributedString.Key.font :  UIFont.systemFont(ofSize: 20), NSAttributedString.Key.foregroundColor : UIColor.black]
                    let attributedString1 = NSMutableAttributedString(string: String(name),attributes:attrs1)
                    let attributedString2 = NSMutableAttributedString(string: self.phrase, attributes: attrs2)
                    
                    titleLabel.attributedText = attributedString1
//                    titleLabel.attributedText = attributedString2
                }
            }
        } catch {
            print("Regex was bad!")
        }

这是一个可行的解决方案(具有可在 Playgrounds 中使用的额外初始值)。

想法是什么:
直接在NS(Mutable)AttributedString上工作。 改变正则表达式模式,让你知道什么是真正的全范围,什么是“第一”的范围。
反向枚举匹配项(因为您将修改字符串,所以范围之后将无效,因为替换的长度不会相同)

let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
titleLabel.backgroundColor = .blue


let string = "This is my text=\"first\" test!"
let attributedString = NSMutableAttributedString(string: string, attributes: [NSAttributedString.Key.font :  UIFont.systemFont(ofSize: 20), NSAttributedString.Key.foregroundColor : UIColor.black])

let pattern = "text=\"([\\w\\s]+)\""

do {
    let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
    let matches = regex.matches(in: attributedString.string, options: [], range: NSRange(location: 0, length: attributedString.length))

    for match in matches.reversed() {
        let globalNSRange = match.range
        let worldNSRange = match.range(at: 1)
        let replacement = NSMutableAttributedString(attributedString: attributedString.attributedSubstring(from: worldNSRange))
        replacement.addAttributes([NSAttributedString.Key.font :  UIFont.systemFont(ofSize: 20),
                                   NSAttributedString.Key.foregroundColor : UIColor.green],
                                  range: NSRange(location: 0, length: replacement.length))
        attributedString.replaceCharacters(in: globalNSRange, with: replacement)
    }

    titleLabel.attributedText = attributedString
} catch {
    print("Regex was bad: \(error)") //Print useful information on why it failed, like the actual thrown error
}

return titleLabel

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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