如何将特定单词替换为 swift 中的 NSAttributedString
How to replace specific word to NSAttributedString in swift
我想替换字符串中的所有特定单词。
例如)
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"
我想要结果 -> "apple(change background color) is red. apple(change background color) is green.
我该怎么办?
你可以通过正则表达式来做到
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)
我想替换字符串中的所有特定单词。
例如)
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"
我想要结果 -> "apple(change background color) is red. apple(change background color) is green.
我该怎么办?
你可以通过正则表达式来做到
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)