gpt4 book ai didi

swift - 在一个字符串中多次使用 NSAttributedString

转载 作者:搜寻专家 更新时间:2023-10-31 22:24:11 27 4
gpt4 key购买 nike

我有一个字符串,例如 "F (R U R' U') (R U R' U') (R U R' U') F'"。我正在使用 NSAttributedString 搜索方括号 (R U R' U') 中的文本,并将其替换为相同的文本,只是颜色不同。我使用的代码是

let mutableAttributedString = NSMutableAttributedString(string: algToShow) 
var searchRange = NSRange(location: 0, length: algToShow.count)
var foundRange1 = NSRange()
foundRange1 = (algToShow as NSString).range(of: "(R U R' U')", options: NSString.CompareOptions.caseInsensitive, range: searchRange)
if foundRange1.location != NSNotFound || foundRange2.location != NSNotFound || foundRange3.location != NSNotFound || foundRange4.location != NSNotFound || foundRange5.location != NSNotFound {
// found an occurrence of the substring! do stuff here
searchRange.location = foundRange1.location + foundRange1.length
mutableAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: foundRange1)

但是,它只突出显示第一组文本/括号;其他人被完全忽略。问题是如何检查括号出现了多少次,并替换它们的每个实例?

谢谢。

最佳答案

这是正则表达式模式 \((.*?)\) 可以找到括号内的匹配项,请 test模式

你可以使用下面的方法并传递上面的模式

func regexMatches(_ pattern: String, string: String) throws -> [NSTextCheckingResult]? {
let regex = try NSRegularExpression(pattern: pattern)
let range = NSRange(string.startIndex..<string.endIndex, in: string)
return regex.matches(in: string, options: [], range: range)
}

用法

let algToShow = "F (R U R' U') (R U R' U') (R U R' U') F'"
let mutableAttributedString = NSMutableAttributedString(string: algToShow)
if let matches = try? regexMatches("\\((.*?)\\)", string: algToShow) {
for match in matches {
mutableAttributedString.addAttribute(.foregroundColor, value: UIColor.red, range: match.range)
}
}

关于swift - 在一个字符串中多次使用 NSAttributedString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56063459/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com