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

查看:176
本文介绍了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)
}

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

I want to be able to extract out the last two numbers captured (\d\d) 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天全站免登陆