我正在尝试在 Swift 3 中做一个简单的正则表达式,从输入字符串中提取一个数字。
由于我不熟悉 iOS,事实证明这是一个相当大的挑战。我高度怀疑我的错误在于同时使用了 String
和 NSString
。
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 itsrange
property, and the range of each individual capture group via itsrangeAt(_:)
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/