gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:59:45 25 4
gpt4 key购买 nike

我有以下代码(在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com