Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the substrings from the NSTextCheckingResult objects in swift?

Tags:

swift2

I wonder how it is possible to find substrings from a NSTextCheckingResult object. I have tried this so far:

import Foundation {
    let input = "My name Swift is Taylor Swift "
    let regex = try NSRegularExpression(pattern: "Swift|Taylor", options:NSRegularExpressionOptions.CaseInsensitive) 
    let matches = regex.matchesInString(input, options: [], range:   NSMakeRange(0, input.characters.count))
    for match in matches {
    // what will be the code here?
}
like image 296
Devian Avatar asked Mar 18 '16 03:03

Devian


2 Answers

Try this:

import Foundation

let input = "My name Swift is Taylor Swift "// the input string where we will find for the pattern
let nsString = input as NSString

let regex = try NSRegularExpression(pattern: "Swift|Taylor", options: NSRegularExpressionOptions.CaseInsensitive)
//matches will store the all range objects in form of NSTextCheckingResult 
let matches = regex.matchesInString(input, options: [], range: NSMakeRange(0, input.characters.count)) as Array<NSTextCheckingResult>

for match in matches {
    // what will be the code
    let range = match.range
    let matchString = nsString.substringWithRange(match.range) as String
    print("match is \(range) \(matchString)")
}
like image 101
Michael Dautermann Avatar answered Nov 01 '22 14:11

Michael Dautermann


Here is code that works for Swift 3. It returns array of String

    results.map {
        String(text[Range($0.range, in: text)!])
    }

So overall example could be like this:

    let regex = try NSRegularExpression(pattern: regex)
    let results = regex.matches(in: text,
                                range: NSRange(text.startIndex..., in: text))
    return results.map {
        String(text[Range($0.range, in: text)!])
    }
like image 39
Danil Avatar answered Nov 01 '22 14:11

Danil