mr_ivan777 mr_ivan777 - 2 months ago 5x
iOS Question

Swift StringBetweenString function

I try to make simple swift application for iOS.
I'm new in Swift, and IOS developing. I need to get substring between two strings from my text. For example, I have text "" and I want to get substring between "://" and ".".

I don't know, how I can do that.

I try to use regular expressions, but I think, it's bad way.

TY for answers, and sorry for my english.


A couple of options:

  1. Regular expressions work well. See ICU User Guide: Regular Expressions


    let us = ""
    let range = us.rangeOfString("(?<=://)[^.]+(?=.)", options:.RegularExpressionSearch)
    if range != nil {
        let found = us.substringWithRange(range!)
        println("found: \(found)") // found: google


        (?<=://) means preceded by ://  
        [^.]+    means any characters except .  
        (?=.)    means followed by .  
  2. NSScanner is also a good method. See Apple's NSScanner Class Reference


    let us = ""
    let scanner = NSScanner(string:us)
    var scanned: NSString?
    if scanner.scanUpToString("://", intoString:nil) {
        scanner.scanString("://", intoString:nil)
        if scanner.scanUpToString(".", intoString:&scanned) {
            let result: String = scanned as String
            println("result: \(result)") // result: google