小编典典

Swift 3-如何提取正则表达式中捕获的组?

swift

我正在使用Swift 3并尝试访问捕获的组。

let regexp = "((ALREADY PAID | NOT ALR | PROVIDER MAY | READY | MAY BILL | BILL YOU | PAID)((.|\\n)*))(( \\d+)(\\.+|-+)(\\d\\d))"

// check if some substring is in the recognized text
if let range = stringText.range(of:regexp, options: .regularExpression) {
    let result = tesseract.recognizedText.substring(with:range)
}

我希望能够提取出捕获的最后两个数字(\d\d),所以如果文本为:ALREADY PAID asfasdfadsfasdf 39.15,它将提取出15。这是显示我想要的正则表达式生成器。通常,我能够$8提取出第8个组,但是我不知道如何在Swift 3中执行此操作。

http://regexr.com/3fh1e


阅读 296

收藏
2020-07-07

共1个答案

小编典典

但是我不知道如何在Swift 3中做到这一点。

当您收到来自NSRegularExpression的匹配项时,您将获得一个NSTextCheckingResult。您致电rangeAt以获取特定的捕获组。

例:

let s = "hey ho ha"
let pattern = "(h).*(h).*(h)"
// our goal is capture group 3, "h" in "ha"
let regex = try! NSRegularExpression(pattern: pattern)
let result = regex.matches(in:s, range:NSMakeRange(0, s.utf16.count))
let third = result[0].rangeAt(3) // <-- !!
third.location // 7
third.length // 1
2020-07-07