You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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和Swift Range<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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.02 03:04:56