Swift 3 - 如何在正则表达式中提取捕获的组? [英] Swift 3 - How do I extract captured groups in regular expressions?

查看:14
本文介绍了Swift 3 - 如何在正则表达式中提取捕获的组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Swift 3 and trying to access captured groups.

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)
}

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

I want to be able to extract out the last two numbers captured (dd) so if the text was: ALREADY PAID asfasdfadsfasdf 39.15, it would extract 15. Here is a regex builder that shows what I want. Normally, I would be able to do $8 to get the 8th group that was extracted but I don't know how to do that in Swift 3.

http://regexr.com/3fh1e

推荐答案

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

but I don't know how to do that in Swift 3.

当您收到来自 NSRegularExpression 的匹配项时,您会得到一个 NSTextCheckingResult.您调用 rangeAt 以获取特定捕获组.

When you receive a match from NSRegularExpression, what you get is an NSTextCheckingResult. You call rangeAt to get a specific capture group.

示例:

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

这篇关于Swift 3 - 如何在正则表达式中提取捕获的组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆