Swift 在属性字符串中查找和更改范围
Swift finding and changing range in attributed string
更改此字符串的最佳方法是什么:
"gain quickness for 5 seconds. <c=@reminder>(Cooldown: 90s)</c> only after"
转换为属性字符串,同时去掉 <> 中的部分,我想更改 (Cooldown: 90s) 的字体。我知道如何更改和制作 NSMutableAttributedStrings,但在这种情况下我仍然坚持如何定位和更改 (Cooldown: 90s)。 <c=@reminder>
和 </c>
之间的文本会发生变化,因此我需要使用它们来找到我需要的内容。
这些似乎是用于此目的的指标我只是不知道。
首先,您需要一个正则表达式来查找和替换所有标记的字符串。
查看字符串,一种可能的正则表达式可能是 <c=@([a-zA-Z-9]+)>([^<]*)</c>
。请注意,仅当标签之间的字符串不包含 <
字符时才会起作用。
现在我们有了正则表达式,我们只需要将它应用到输入字符串上:
let str = "gain quickness for 5 seconds. <c=@reminder>(Cooldown: 90s)</c> only after"
let attrStr = NSMutableAttributedString(string: str)
let regex = try! NSRegularExpression(pattern: "<c=@([a-zA-Z-9]+)>([^<]*)</c>", options: [])
while let match = regex.matches(in: attrStr.string, options: [], range: NSRange(location: 0, length: attrStr.string.utf16.count)).first {
let indicator = str[Range(match.range(at: 1), in: str)!]
let substr = str[Range(match.range(at: 2), in: str)!]
let replacement = NSMutableAttributedString(string: String(substr))
// now based on the indicator variable you might want to apply some transformations in the `substr` attributed string
attrStr.replaceCharacters(in: match.range, with: replacement)
}
更改此字符串的最佳方法是什么:
"gain quickness for 5 seconds. <c=@reminder>(Cooldown: 90s)</c> only after"
转换为属性字符串,同时去掉 <> 中的部分,我想更改 (Cooldown: 90s) 的字体。我知道如何更改和制作 NSMutableAttributedStrings,但在这种情况下我仍然坚持如何定位和更改 (Cooldown: 90s)。 <c=@reminder>
和 </c>
之间的文本会发生变化,因此我需要使用它们来找到我需要的内容。
这些似乎是用于此目的的指标我只是不知道。
首先,您需要一个正则表达式来查找和替换所有标记的字符串。
查看字符串,一种可能的正则表达式可能是 <c=@([a-zA-Z-9]+)>([^<]*)</c>
。请注意,仅当标签之间的字符串不包含 <
字符时才会起作用。
现在我们有了正则表达式,我们只需要将它应用到输入字符串上:
let str = "gain quickness for 5 seconds. <c=@reminder>(Cooldown: 90s)</c> only after"
let attrStr = NSMutableAttributedString(string: str)
let regex = try! NSRegularExpression(pattern: "<c=@([a-zA-Z-9]+)>([^<]*)</c>", options: [])
while let match = regex.matches(in: attrStr.string, options: [], range: NSRange(location: 0, length: attrStr.string.utf16.count)).first {
let indicator = str[Range(match.range(at: 1), in: str)!]
let substr = str[Range(match.range(at: 2), in: str)!]
let replacement = NSMutableAttributedString(string: String(substr))
// now based on the indicator variable you might want to apply some transformations in the `substr` attributed string
attrStr.replaceCharacters(in: match.range, with: replacement)
}