简体   繁体   中英

How do I extract a particular sentence from a string using NSRange?

This is my code:

regex.enumerateMatchesInString(parsingMemo.string, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, parsingMemo.length), usingBlock: { (match: NSTextCheckingResult?,_, _) -> Void in
let trange = match!.rangeAtIndex(0)
let range = Range(start: trange.location, end: trange.length)
var insideString: String = parsingMemo.string.substringWithRange(NSMakeRange(trange.location,trange.length) 

The code gives me the following error:

Cannot convert value of type 'NSRange' (aka '_NSRange') to expected argument type 'Range' (aka 'Range')

How can I fix my code?

You need to convert the NSRange that you were given into a Swift Range . Something like this should work:

let start = parsingMemo.string.characters.startIndex.advancedBy(trange.location)
let end = start.advancedBy(trange.length)

var insideString: String = parsingMemo.string.substringWithRange(start..<end) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM