swift - 使用 NSRegularExpression 结果对字符串进行子字符串化的正确方法是什么?

标签 swift

我在使用此功能时遇到问题:

    private func regexFirstGroup(in intext: String, pattern: String) -> String? {
    do {
        let nsrange = NSRange(intext.startIndex..<intext.endIndex, in: intext)
        let regex = try NSRegularExpression(pattern: pattern, options: [NSRegularExpression.Options.dotMatchesLineSeparators])
        if let match = regex.firstMatch(in: intext, options: [], range: nsrange) {
            guard let mrange = Range(match.range(at: 1), in:intext) else {
                return nil
            }
            return intext.substring(with: mrange)
        }
    } catch {
        print("Pattern \(pattern) compiled with error: \(error)")
        return nil
    }
    return nil
}

符合:

return intext.substring(with: mrange)

给出弃用警告: 'substring(with:)' 已弃用:请使用字符串切片下标。

当我将它切换到预期的 swift5 方式时:

return intext[mrange]

比它给出一个错误: 下标 'subscript(_:)' 要求类型 'String.Index' 和 'Int' 是等价的

这很奇怪,因为下标应该与 String.Index 类型一起使用,并且在快速帮助中检查 mrange 常量显示:

Declaration
let mrange: Range<String.Index>

我没有使用 import Foundation atm。

最佳答案

你应该使用 subscript(_:)

return String(intext[mrange])

关于swift - 使用 NSRegularExpression 结果对字符串进行子字符串化的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56207584/

相关文章:

ios - showViewController 不工作

swift - 侧面菜单 Controller

ios - 在 Swift/iOS 中从 UITableView 删除行并从 NSUserDefaults 更新数组的正确方法

ios - 为什么 iOS 13 Core Location 有时会在后台返回坐标为 0,0 的位置?

ios - iOS 10 上的 UIVisualEffectView 掩码

ios - 无法从 TableView 中的索引路径获取正确的元素

swift - "Argument type string does not conform to expected type decoder"尝试使用可编码协议(protocol)获取 JSON

ios - 在 ios swift 上购物添加到购物车图标角标(Badge)通知

ios - 服务 API 调用阻止 UITableViewController 中的 UI

ios - 无法获取 CoreData 以删除对象