0

我想在 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)

但我不知道有什么工作要做。

请如果有人可以给我一些帮助!

非常感谢

4

1 回答 1

1

我现在能想到的唯一选择是使用原始字符串并修复格式错误的范围。试试这样:

var str = """
circular para poder realizar sus tareas laborales correspondientes a las actividades de comercialización de alimentos
"""
do {
    let regex = try NSRegularExpression(pattern: ".", options: .caseInsensitive)
    let results = regex.matches(in: str, options: .withoutAnchoringBounds, range: NSRange(location: 0, length: str.utf16.count))
    var badrange: NSRange?
    results.forEach { result in
        guard let range = Range(result.range, in: str) else {
            if badrange != nil {
                badrange!.length += 1
                if let range = Range(badrange!, in: str) {
                    let newStr = str[range]
                    print(newStr)
                }
            } else {
                badrange = result.range
            }
            return
        }
        let newStr = str[range]
        print(newStr)
        badrange = nil
    }
} catch {
    print(error)
}
于 2020-09-11T22:22:44.953 回答