Search code examples
swiftstringnsstringnsattributedstring

How to replace specific word to NSAttributedString in swift


I want to replace all the specific words in a string.

For example)

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

I want to change background the word "apple" only in the sentence.

So I tried the following.

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)

but result that.

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

I want result -> "apple(change background color) is red. apple(change background color) is green.

What should I do?


Solution

  • You can do it by regular expression

    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)