Yac*_*mba 3 xcode nsattributedstring swift
例如,我有一个字符串"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)
Run Code Online (Sandbox Code Playgroud)
但是,它仅突出显示第一组文本/括号;其他的则完全被忽略。问题是如何检查括号出现的次数,并替换它们的每个实例?
谢谢。
这是正则表达式模式\((.*?)\),将查找括号内出现的情况,请测试该模式
您可以使用以下方法并传递上面的模式
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)
}
Run Code Online (Sandbox Code Playgroud)
用法
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)
}
}
Run Code Online (Sandbox Code Playgroud)