如何将Regex应用于AttributedString?使用遇问题求助
问题解决步骤
一、找不到String的Regex相关方法
- 若使用Swift 5.7及以上版本,Apple推出了原生
Regex类型,替代旧的range(of:)、matches(:_)等NSString桥接方法。调用方式示例:// 创建Regex实例 let regex = try! Regex(#"\w+"#) // 匹配所有结果 let matches = regex.matches(in: targetString) - 若要使用旧的NSString桥接方法,需将Swift String转为NSString再调用:
let nsString = targetString as NSString let range = nsString.range(of: pattern, options: .regularExpression) let allMatches = nsString.matches(of: pattern, options: .regularExpression) - 排查Xcode缓存问题:执行
Cmd+Shift+K清理编译文件夹,再重新编译项目,缓存异常可能导致Foundation框架方法无法正常识别。
二、Regex与AttributedString结合实现高亮
以下是基础实现示例,针对不同语法元素匹配并添加属性:
import Foundation let sourceText = "func calculate(_ num: Int) -> Int { return num * 2 }" var attributedText = AttributedString(sourceText) // 匹配函数关键字 do { let funcRegex = try Regex(#"\bfunc\b"#) for match in funcRegex.matches(in: attributedText) { attributedText[match.range].foregroundColor = .systemBlue attributedText[match.range].font = .boldSystemFont(ofSize: 14) } } catch { print("Regex编译失败:\(error)") } // 匹配类型关键字 do { let typeRegex = try Regex(#"\b(Int)\b"#) for match in typeRegex.matches(in: attributedText) { attributedText[match.range].foregroundColor = .systemPurple } } catch { print("Regex编译失败:\(error)") }
- 注意事项:如果使用
NSAttributedString而非SwiftUI/Foundation的AttributedString,需要处理NSRange和SwiftRange<String.Index>的转换,示例:let nsText = sourceText as NSString let nsRange = nsText.range(of: #"\bfunc\b"#, options: .regularExpression) if nsRange.location != NSNotFound, let swiftRange = Range(nsRange, in: sourceText) { let mutableAttributed = NSMutableAttributedString(string: sourceText) mutableAttributed.addAttribute(.foregroundColor, value: UIColor.systemBlue, range: nsRange) }
内容的提问来源于stack exchange,提问作者Ryan Bae
相关产品推荐
相关产品推荐

