Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBetweenString function

I need to get substring between two strings from my text. For example, I have text "http://google.com" 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.

like image 699
mr_ivan777 Avatar asked Dec 02 '22 15:12

mr_ivan777


2 Answers

A couple of options:

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

    Example:

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

    Notes:

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

    Example:

    let us = "http://google.com"
    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
        }
    }
    
like image 113
zaph Avatar answered Dec 09 '22 09:12

zaph


You can use the regular Expression

://.+.

it matches to

://google.

in this code:

var yourURL: NSString = "http://google.com" // this is your input and could be any URL
var regex: NSRegularExpression = NSRegularExpression.regularExpressionWithPattern("://.+\\.", options: NSRegularExpressionOptions.fromMask(UInt(0)), error: nil) // need double backspace because of backspace in String is \\ not \
var needleRange = regex.rangeOfFirstMatchInString(yourURL, options:NSMatchingOptions.Anchored, range: NSMakeRange(0, yourURL.length))
var needle: NSString = yourURL.substringWithRange(needleRange)

Now you can remove the first 3 symbols and the last one and you got

google

with this code:

import Foundation

var halfURL: NSString = "://google."
var prefix: NSString = "://"
var suffix: NSString = "."
var needleRange: NSRange =  NSMakeRange(prefix.length, halfURL.length - prefix.length -     suffix.length)
var needle: NSString = halfURL.substringWithRange(needleRange)
// needle is now 'google'
like image 45
Binarian Avatar answered Dec 09 '22 07:12

Binarian