Reputation: 1678
I have this regex expression that works on http://www.regexr.com but not in iOS. Anyone know what's wrong?
let regex = NSRegularExpression(pattern: "v=(.+?)(?=\\s|&)", options: NSRegularExpressionOptions.CaseInsensitive, error: &error)
Original regex: v=(.+?)(?=\s|&)
Regex is applied over this test URLs (separated):
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
Thanks!
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
Upvotes: 3
Views: 1386
Reputation: 539685
Your pattern does not find "v=..." at the end of the string, because (?=\\s|&)
expects
a following white space or "&" character. With "v=(.+?)(?=$|&)"
you should get the expected result.
Upvotes: 3