Mar*_*ark 25 regex iphone xcode
我有一个像'stackoverflow.html'这样的字符串,在正则表达式'stack(.).html'中我希望得到(.)中的值.
我只能找到NSPredicate:
NSString *string = @"stackoverflow.html";
NSString *expression = @"stack(.*).html";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", expression];
BOOL match = [predicate evaluateWithObject:string]
Run Code Online (Sandbox Code Playgroud)
但是当我使用NSRegularExpression时,这只会告诉我有一个匹配并且不返回字符串:
NSRange range = [string rangeOfString:expression options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
if (range.location == NSNotFound) return nil;
NSLog (@"%@", [string substringWithRange:(NSRange){range.location, range.length}]);
Run Code Online (Sandbox Code Playgroud)
它会给我一个完整的字符串,stackoverflow.html,但我只对(.*)中的那些感兴趣.我想要'溢出'回来.在PHP中这很容易做到,但是如何在xCode for iOS中实现这一点?
从逻辑上讲,如果我这样做:
NSInteger firstPartLength = 5;
NSInteger secondPartLength = 5;
NSLog (@"%@", [string substringWithRange:(NSRange){range.location + firstPartLength, range.length - (firstPartLength + secondPartLength)}]
Run Code Online (Sandbox Code Playgroud)
它给了我属性结果'溢出'.但问题是在很多情况下我不知道第一部分或第二部分的长度.那么有没有办法让我得到应该在(.*)的值?
或者我必须通过找到(.)的位置并从那里计算第一和第二部分来决定选择最丑的方法吗?但是在正则表达式中你可能也有([az])但是然后用丑陋的方式使用另一个正则表达式获取()之间的值的位置然后用它来计算左右部分?如果我有更多,会发生什么?比如'A(.)应该找到(.*)的答案.我希望有一个数组作为结果,值[0]是A之后的值,[1]是之后的值.
我希望我的问题很明确.
提前致谢,
use*_*008 91
在iOS 4.0+中,您可以使用NSRegularExpression:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"stack(.*).html" options:0 error:NULL];
NSString *str = @"stackoverflow.html";
NSTextCheckingResult *match = [regex firstMatchInString:str options:0 range:NSMakeRange(0, [str length])];
// [match rangeAtIndex:1] gives the range of the group in parentheses
// [str substringWithRange:[match rangeAtIndex:1]] gives the first captured group in this example
Run Code Online (Sandbox Code Playgroud)
您需要 RegexKitLite 库来执行正则表达式匹配:
http://regexkit.sourceforge.net/RegexKitLite/
之后,它几乎与您在 PHP 中所做的完全一样。
我将添加一些代码来帮助您:
NSString *string = @"stackoverflow.html";
NSString *expression = @"stack(.*)\\.html";
NSString *matchedString = [string stringByMatching:expression capture:1];
Run Code Online (Sandbox Code Playgroud)
匹配的字符串是@“overflow”,这应该正是您所需要的。