Alex Bailey
Alex Bailey

Reputation: 1512

Swift extract string from string

I have a string that looks like:

"OS-MF sessionId='big_super-long-id_string', factor='PASSCODE'"

But I need to get the sessionId that is in that string. Can someone help me in swift? I've tried regex but can't get it to work.

Upvotes: 0

Views: 520

Answers (2)

Victor Sigler
Victor Sigler

Reputation: 23451

If you want to use Regular Expression you can use the following fucntion to match any occurrence of the pattern:

func matchesForRegexInText(regex: String!, text: String!) -> [String] {

    let regex = NSRegularExpression(pattern: regex, options: nil, error: nil)!

    let nsString = text as NSString
    let results = regex.matchesInString(text,
        options: nil, range: NSMakeRange(0, nsString.length))
        as! [NSTextCheckingResult]

    return map(results) { nsString.substringWithRange($0.range)}
}

And you can test it with the following regex :

let myStringToBeMatched = "OS-MF sessionId='big_super-long-id_string', factor='PASSCODE'"        

var results = self.matchesForRegexInText("(?<=sessionId=')(.*)(?=',)", text: myStringToBeMatched)
for item in results {
     println(item)
}

The output should be :

big_super-long-id_string

Notes:

(?<=sessionId=') means preceded by sessionId='  
(.*)             means any character zero or more times     
(?=',)           means followed by ', 

You can read more about Regex patterns here

I hope this help you.

Upvotes: 4

Leo Dabus
Leo Dabus

Reputation: 236260

let input = "OS-MF sessionId='big_super-long-id_string', factor='PASSCODE'"
let sessionID = input.componentsSeparatedByString("sessionId='").last!.componentsSeparatedByString("',").first!

println(sessionID) // "big_super-long-id_string"

Upvotes: 1

Related Questions