3

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

Faris Zacina
  • 14,056
  • 7
  • 62
  • 75
mhergon
  • 1,688
  • 1
  • 18
  • 39

1 Answers1

3

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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Martin, the result is not as expected: http://regexr.com/39lof Not all cases are met – mhergon Oct 08 '14 at 20:12
  • @mhergon: It seems that http://regexr.com treats `\s` and `$` differently from Swift with `NSRegularExpression`. I did test this with Swift code where it produced the expected result. – Martin R Oct 08 '14 at 20:14
  • Ooh, that's right! Sorry! I tried with "v=(.+?)(?=$|&|\\s)" and works, but your solution "v=(.+?)(?=$|&)" also works. Thanks! – mhergon Oct 08 '14 at 20:19