NSRegularExpression 和 preg 之间的区别
我一直在努力使用 NSRegularExpression,是否有一些我不知道的正则表达式的主要区别?
我正在尝试这样做:
NSString *str = @"&url=http%3A%2F%2Fi.hello.com/random/depeth/in/string.JPG%3Fset_id"
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:@"i(.+?)%3Fset_id"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:str
options:0 range:NSMakeRange(0, [str length])];
我希望 rangeOfFirstMatch 成为 .hello.com/random/depeth/in/string.JPG
正则表达式“i(.+?)%3Fset_id”的范围在 preg 中似乎工作正常。
有点迷失了。
提前致谢。
I have been struggling with using NSRegularExpression, is there some major difference from Regex that I am unaware of?
I am trying this:
NSString *str = @"&url=http%3A%2F%2Fi.hello.com/random/depeth/in/string.JPG%3Fset_id"
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:@"i(.+?)%3Fset_id"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:str
options:0 range:NSMakeRange(0, [str length])];
I would like rangeOfFirstMatch to be the range of .hello.com/random/depeth/in/string.JPG
regex "i(.+?)%3Fset_id" seems to work fine in preg.
Kind of lost.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
rangeOfFirstMatchInString:...
不会执行您所期望的操作:它会查找整个正则表达式的字符串中的第一个匹配项。你想要的是这样的:(另请注意,大写非全局非常量不是 Cocoa 约定,尽管这显然不会破坏你的代码。)
rangeOfFirstMatchInString:…
doesn't do what you're expecting: It finds the first match in the string of the entire regex. What you want is something like:(Also note that capitalizing non-global non-constants isn't Cocoa convention, though that obviously won't break your code.)