为什么正则表达式不起作用?迅速

时间:2014-10-08 19:18:07

标签: regex url swift nsregularexpression

我有这个正则表达式,适用于http://www.regexr.com但不适用于iOS。谁知道什么是错的?

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

原始正则表达式: v =(。+?)(?= \ s |&)

正则表达式应用于此测试网址(已分隔):

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

谢谢!

编辑1:

以下是代码:

// 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)

“匹配”是零!

编辑2:

预期结果:regexr.com/39loc

1 个答案:

答案 0 :(得分:3)

您的模式找不到" v = ..."在字符串的结尾,因为(?=\\s|&)期望 以下白色空间或"&"字符。使用"v=(.+?)(?=$|&)",您应该得到预期的结果。