如何对 Swift AttributedString 应用正则表达式?
可以先把 AttributedString 的字符内容转成 String,在普通字符串上完成正则匹配,再将匹配范围转换为 AttributedString.Index,最后设置颜色等属性。仅导入 Foundation 不会让 AttributedString 自动拥有 String 上的全部匹配方法。
String 应该使用哪个正则 API?
这几种调用方式的接收对象和参数类型不同:
- 查找第一个匹配范围:
text.range(of: pattern, options: .regularExpression),其中pattern是字符串。 - 使用 Foundation 查找全部匹配:
regex.matches(in: text, options: [], range: searchRange),其中regex是NSRegularExpression。 - 使用 Swift 原生
Regex:在支持该 API 的工具链和运行环境中调用text.matches(of: regex)或text.firstMatch(of: regex)。参数应是Regex,不能直接传入普通模式字符串。
例如,只查找第一个关键字时可以这样写:
import Foundation
let text = "let value = 42"
let range = text.range(
of: #"\b(let|var|func)\b"#,
options: .regularExpression
)
range(of:options:range:locale:) 返回第一个匹配范围;原生 Regex 的匹配入口使用 matches(of:) 等名称。可参阅 String 范围查找文档和 Regex 文档。
如何把全部匹配应用到 AttributedString?
下面使用 NSRegularExpression 查找关键字,再通过 SwiftUI 的颜色属性,将传入的 AttributedString 中的匹配项设为蓝色。示例要求目标环境支持 AttributedString 和所用的索引转换 API。
import Foundation
import SwiftUI
func highlightKeywords(
in input: AttributedString
) throws -> AttributedString {
var result = input
let text = String(result.characters)
let regex = try NSRegularExpression(
pattern: #"\b(let|var|func)\b"#
)
let searchRange = NSRange(
text.startIndex..<text.endIndex,
in: text
)
for match in regex.matches(
in: text,
options: [],
range: searchRange
) {
guard
let stringRange = Range(match.range, in: text),
let lower = AttributedString.Index(
stringRange.lowerBound,
within: result
),
let upper = AttributedString.Index(
stringRange.upperBound,
within: result
)
else {
continue
}
result[lower..<upper].foregroundColor = .blue
}
return result
}
// 在 SwiftUI 视图中,可将返回值交给 Text 显示。
do {
let source = AttributedString("let value = 42\nvar count = 0")
let highlighted = try highlightKeywords(in: source)
// Text(highlighted)
} catch {
print("Invalid regular expression: \(error)")
}
NSRegularExpression 的匹配结果提供 NSRange,而富文本下标需要自己的索引类型。示例依次完成了范围转换:NSRange → Range<String.Index> → Range<AttributedString.Index>。相关接口见 NSRegularExpression.matches 文档和 AttributedString.Index 文档。
已经导入 Foundation,为什么仍然找不到方法?
先检查调用对象的实际类型。AttributedString、AttributedString.CharacterView 和 String 是不同的类型。需要调用字符串匹配方法时,先得到普通字符串:
let text: String = String(attributed.characters)
然后检查参数标签。range(of:options:)、matches(of:) 和 matches(in:options:range:) 是不同的接口,不能混用。对于原生 Regex,还需要确认 Xcode 所带的 Swift 工具链和部署目标是否支持对应 API。
原问题没有提供具体调用代码、编译器报错或 Xcode/Swift 版本,因此无法确定方法不可见的唯一原因,也不能据此判断为 Xcode 故障。
范围转换和高亮有哪些注意事项?
NSRange使用 UTF-16 偏移,不能直接用text.count作为匹配范围长度。示例通过NSRange(_:in:)创建搜索范围,避免混淆字符数量和 UTF-16 长度。- 匹配使用的
String必须与目标富文本的字符内容保持一致。如果在匹配和应用属性之间插入、删除或替换了文字,应重新匹配并转换范围。 - 示例只修改颜色,不修改文字。
.foregroundColor = .blue使用 SwiftUI 属性;UIKit 或 AppKit 项目应选择对应的属性作用域和颜色类型。 - 示例中的模式只识别几个关键字,也可能匹配字符串字面量或注释里的同名文本。用于实验可以;如果需要准确处理语法上下文,应增加词法分析或语法解析。
备注:内容仅供参考。
