Why is the regex not working? swift

I have this regex expression that works on http://www.regexr.com but not on iOS. Does anyone know what happened?

let regex = NSRegularExpression(pattern: "v=(.+?)(?=\\s|&)", options: NSRegularExpressionOptions.CaseInsensitive, error: &error)

      

Original regex: v = (. +?) (? = \ S | &)

The regex is applied to these test urls (stripped):

https://www.youtube.com/watch?v=sjifp5oi6dE
https://www.youtube.com/watch?v=gdigMMGadDM&feature=relmfu
https://www.youtube.com/watch?v=gdigMMGadDM&feature=relmfu&asdsadsa
https://www.youtube.com/watch?v=gdigMMGadDM&feature=relmfu&asdsadsa&asdfasdasdasQ%4&asdsadsad
https://www.youtube.com/watch?feature=relmfu&asdsadsa&asdfasdasdasQ%4&asdsadsad&v=gdigMMGadDM

      

Thank!

EDIT 1:

Here's the code:

// Get video ID
var error: NSError?
let regex = NSRegularExpression(pattern: "v=(.+?)(?=\\s|&)", options: NSRegularExpressionOptions.CaseInsensitive, error: &error)
println(originalURL)
println(regex)
let match: NSTextCheckingResult? = regex.firstMatchInString(originalURL, options: NSMatchingOptions(0), range: NSMakeRange(0, countElements(originalURL)))
println(match)
let videoID = (originalURL as NSString).substringWithRange(match!.range).stringByReplacingOccurrencesOfString("v=", withString: "")
println(videoID)

      

"match" is nil!

EDIT 2:

Expected results: regexr.com/39loc

+3


source to share


1 answer


Your pattern does not find "v = ..." at the end of the line because it (?=\\s|&)

expects the next white space or "&" character. With, "v=(.+?)(?=$|&)"

you should get the expected result.



+3


source







All Articles