Search code examples
iosstringswiftsubstring

Swift Get string between 2 strings in a string


I am getting a string from html parse that is;

string = "javascript:getInfo(1,'Info/99/something', 'City Hall',1, 99);"

my code is something like

var startIndex = text.rangeOfString("'")
var endIndex = text.rangeOfString("',")
var range2 = startIndex2...endIndex
substr= string.substringWithRange(range)

i am not sure if my second splitting string should be "'" or "',"

i want my outcome as

substr = "Info/99/something"

Solution

  • I'd use a regular expression to extract substrings from complex input like this.

    Swift 3.1:

    let test = "javascript:getInfo(1,'Info/99/something', 'City Hall',1, 99);"
    
    if let match = test.range(of: "(?<=')[^']+", options: .regularExpression) {
        print(test.substring(with: match))
    }
    
    // Prints: Info/99/something
    

    Swift 2.0:

    let test = "javascript:getInfo(1,'Info/99/something', 'City Hall',1, 99);"
    
    if let match = test.rangeOfString("(?<=')[^']+", options: .RegularExpressionSearch) {
        print(test.substringWithRange(match))
    }
    
    // Prints: Info/99/something