gpt4 book ai didi

ios - 来自 Regex 的 Swift 3 提取组 - NS 桥接困惑

转载 作者:行者123 更新时间:2023-11-28 12:32:51 25 4
gpt4 key购买 nike

我正在尝试在 Swift 3 中做一个简单的正则表达式,从输入字符串中提取一个数字。

由于我不熟悉 iOS,事实证明这是一个相当大的挑战。我高度怀疑我的错误在于同时使用了 StringNSString

let url = "a5b"
let nsUrl = url as NSString

let regex = try! NSRegularExpression(pattern: "a(\\d)b", options: [])
let matches = regex.matches(in: url, options: [], range: NSRange(location: 0, length: url.characters.count))

somestuff(str: nsUrl.substring(with: matches[1].range))

失败并出现以下异常:

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSSingleObjectArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

正确的匹配和获取号码的方法是什么?

最佳答案

索引从零开始,但捕获的组在范围索引 1

somestuff(str: nsUrl.substring(with: matches[0].rangeAt(1)))

无论如何你应该测试没有匹配......


关于matches(in)的返回值:

An array of NSTextCheckingResult objects. Each result gives the overall matched range via its range property, and the range of each individual capture group via its rangeAt(_:) method. The range {NSNotFound, 0} is returned if one of the capture groups did not participate in this particular match.

注意:range其实和rangeAt(0)是一样的

关于ios - 来自 Regex 的 Swift 3 提取组 - NS 桥接困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41653888/

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