regex - 当没有匹配项或组索引太高时返回 nil

标签 regex swift option-type

我有以下代码(在 Swift 1.2 中),它很大程度上受到 this tutorial on regex expressions 的启发。 (特别是通过给定 playground 中的函数 listGroups):

func groupMatch(pattern: String, string: String, groupIndex: Int) -> String? {
    let regex = NSRegularExpression(pattern: pattern, options: nil, error: nil)
    let range = NSMakeRange(0,count(string))
    let match: NSTextCheckingResult? = regex?.firstMatchInString(string, options: nil, range: range)
    let substring: String? = (string as NSString).substringWithRange(match!.rangeAtIndex(groupIndex))
    if groupIndex < match!.numberOfRanges {
        return substring
    } else {
        return nil
    }
}

这个想法是给定一个模式、一个字符串和一个(正)整数 n 该函数返回与第 n 组匹配的第一个子字符串,如果它存在。例如,

let pat = "aa\\s*(\\d+)\\.(\\d\\d)"
let str = "aa     1234.56  aa 7.89"

let grp1cap = groupMatch(pat, str, 1) // yields "1234"
let grp2cap = groupMatch(pat, str, 2) // yields "56"

到目前为止一切顺利。但是,groupMatch 的定义并没有达到我的预期。下面一行

let grp3cap = groupMatch(pat, str, 3)

似乎没有评估为 nil。我想测试是否有值(value),例如像这样

func test(pat: String, str: String, idx: Int) -> String {
    if let cap = groupMatch(pat, str, idx) {
        return cap
    } else {
        return ("no capture")
    }
}

但是 test(pat, str, 3) 不返回“无捕获”字符串。事实上,它根本不返回任何内容。

groupMatch 的上述定义有什么问题?我如何获得预期的行为?

最佳答案

您试图通过访问一个不存在的组来初始化一个子字符串。因此,在执行 if 条件之前会发生错误。返回 if 中的子字符串:

func groupMatch(pattern: String, string: String, groupIndex: Int) -> String? {
    let regex = NSRegularExpression(pattern: pattern, options: nil, error: nil)
    let range = NSMakeRange(0,count(string))
    let match: NSTextCheckingResult? = regex?.firstMatchInString(string, options: nil, range: range)

    if groupIndex < match!.numberOfRanges { // RIGHT BELOW \/
        return (string as NSString).substringWithRange(match!.rangeAtIndex(groupIndex))
    } else {
        return nil
    }
}

然后,println(grp3cap) 将打印 nilprintln(test(pat, str, 3)) 将打印 没有捕获

关于regex - 当没有匹配项或组索引太高时返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32212464/

相关文章:

ios - Swift 3 解析 youtube 视频不显示结果并不断加载 - IOS 10

swift - 如何在 map 上显示先前拖动或移动的位置的 map

swift - 如何跳出函数外的 guard 语句?

java - 正则表达式: exclusion in character class

php - 如何检查Laravel Hash是否对字符串进行哈希处理?

c++ - 我可以在 Swift 上将一个类传递给同一个类中的函数吗(试图编写一个使用 C++ 和 Swift 语言编写的类)

Scala 围绕更高种类的类型扁平化选项,寻找更惯用的方法

javascript - RegExp 不适用于读取 HTML 文件

javascript - 获取特定两个数字后接下来的 6 个任意数字

swift - 使字典值作为扩展名成为非可选