如何在swift中将特定单词替换为NSAttributedString

时间:2018-03-14 12:50:39

标签: swift string nsstring nsattributedstring

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

例如)

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"

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

我该怎么办?

1 个答案:

答案 0 :(得分: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)