【问题标题】:How to replace specific word to NSAttributedString in swift [duplicate]如何在swift中将特定单词替换为NSAttributedString [重复]
【发布时间】:2018-03-14 12:50:38
【问题描述】:

我想替换字符串中的所有特定单词。

例如)

var str = "apple is red. apple is green"

我只想改变句子中“apple”这个词的背景。

所以我尝试了以下方法。

let resultString = NSMutableAttributedString(string: str)

let apple = NSMutableAttributedString(string: "apple")

apple.addAttribute(NSAttributedStringKey.backgroundColor, value: UIColor.yellow, range: NSRange(location: 0, length: apple.length))

resultString.replaceCharacters(in: (str as NSString).range(of: "apple"), with: apple)

但是结果。

resultString = "apple(change background color) is red. apple(did not change background color) is green"

我想要结果 -> “苹果(改变背景颜色)是红色的。苹果(改变背景颜色)是绿色的。

我该怎么办?

【问题讨论】:

  • range(of:) 将只返回第一次出现,这是正常行为。您需要循环或正则表达式。
  • @Larme 我明白这一点。但我不知道如何实现...
  • @Larme OMG。很好的工作。非常感谢!!!!

标签: swift string nsstring nsattributedstring


【解决方案1】:

你可以通过正则表达式来做到这一点

var str = "apple is red. apple is green"

    let resultString = NSMutableAttributedString(string: str)

    let apple = NSMutableAttributedString(string: "apple")

    apple.addAttribute(NSAttributedStringKey.backgroundColor, value: UIColor.yellow, range: NSRange(location: 0, length: apple.length))

    let components = str.components(separatedBy: " ")

    do {
        let regex = try NSRegularExpression(pattern: "apple", options: NSRegularExpression.Options.caseInsensitive)


        regex.enumerateMatches(in: str, options: [NSRegularExpression.MatchingOptions.reportCompletion], range: NSRange.init(location: 0, length: str.count)) { (result, flags, pointer) in

            resultString.replaceCharacters(in: result?.range(at: 0) ?? NSRange(), with: apple)
        }
    }catch let error {
        print(error)
    }

    print(resultString)

【讨论】:

  • 我试试这个代码。这工作得很好。谢谢你,我选择了这个答案。
猜你喜欢
  • 2021-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-02
  • 1970-01-01
  • 2011-08-02
  • 1970-01-01
相关资源
最近更新 更多