我想在 pdf 中搜索正则表达式,并使用正则表达式的结果为其添加注释。我已经建立了一个简单的函数来做到这一点。正如令人惊叹的社区(用他们的时间帮助我的真正了不起的人)发布的那样,我可以使用decomposedStringWithCompatibilityMapping在 pdf 中正确搜索所需的表达式,但之后当我执行 pdf 选择以找到它的边界时,我遇到不同。我把我的代码和一些图片发给你。
func performRegex(regex:String, on pdfPage:PDFPage) {
guard let pdfString = pdfPage.string?.precomposedStringWithCanonicalMapping else { return }
guard let safeRegex = try? NSRegularExpression(pattern: regex, options: .caseInsensitive) else { return }
let results = safeRegex.matches(in: pdfString, options: .withoutAnchoringBounds, range: NSRange(pdfString.startIndex..., in: pdfString))
pdfPage.annotations.forEach { pdfPage.removeAnnotation($0)}
results.forEach { result in
let bbox = pdfPage.selection(for: result.range)?.bounds(for: pdfPage)
let annotation = PDFAnnotation(bounds: bbox!, forType: .highlight, withProperties: nil)
annotation.color = .yellow
annotation.contents = String(pdfString[Range(result.range, in:pdfString)!])
pdfPage.addAnnotation(annotation)
}
}
问题是,当我这样做并输入此表达式 [0-9] 时,我的所有结果都会发生变化:
虽然如果我不使用 precomposedStringWithCanonicalMapping,我的所有结果都不会改变,但是当我得到一个特殊字符时会遇到错误。
问题(我怀疑)出在这行代码中。
let bbox = pdfPage.selection(for: result.range)?.bounds(for: pdfPage)
但我不知道有什么工作要做。
请如果有人可以给我一些帮助!
非常感谢