0

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.

1
  • Please post your attempt anyway. Commented May 26, 2015 at 21:33

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1
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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.