Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a correct way to substring a string with NSRegularExpression results?

Tags:

swift

I'm having a problem with this function:

    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
}

line with:

return intext.substring(with: mrange)

gives an deprecated warning: 'substring(with:)' is deprecated: Please use String slicing subscript.

and when I switch it to expected swift5 way:

return intext[mrange]

than it gives an error: Subscript 'subscript(_:)' requires the types 'String.Index' and 'Int' be equivalent

This is strange, because subscripting should work with String.Index types, and inspecting mrange constant in quick help shows:

Declaration
let mrange: Range<String.Index>

I'm not using import Foundation atm.

like image 553
helot Avatar asked May 19 '19 12:05

helot


1 Answers

You should use subscript(_:)

return String(intext[mrange])
like image 98
RajeshKumar R Avatar answered Nov 13 '22 05:11

RajeshKumar R