Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone 如何使用正则表达式在iOS中获取匹配?_Iphone_Regex_Xcode - Fatal编程技术网

Iphone 如何使用正则表达式在iOS中获取匹配?

Iphone 如何使用正则表达式在iOS中获取匹配?,iphone,regex,xcode,Iphone,Regex,Xcode,我得到了一个类似于“stackoverflow.html”的字符串,在正则表达式“stack(.).html”中,我希望在(.)中包含该值 我只能找到如下预测: NSString *string = @"stackoverflow.html"; NSString *expression = @"stack(.*).html"; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %

我得到了一个类似于“stackoverflow.html”的字符串,在正则表达式“stack(.).html”中,我希望在(.)中包含该值

我只能找到如下预测:

NSString    *string     = @"stackoverflow.html";
NSString    *expression = @"stack(.*).html";
NSPredicate *predicate  = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", expression];
BOOL match = [predicate evaluateWithObject:string]
但当我使用NSRegularExpression时,这只会告诉我找到了匹配项,而不会返回字符串:

NSRange range = [string rangeOfString:expression options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
if (range.location == NSNotFound) return nil;

NSLog (@"%@", [string substringWithRange:(NSRange){range.location, range.length}]);
它将返回总字符串stackoverflow.html,但我只对(.*)中的内容感兴趣。我想找回“溢出”。在PHP中这很容易做到,但如何在xCode for iOS中做到这一点

从逻辑上讲,如果我愿意这样做:

NSInteger firstPartLength  = 5;
NSInteger secondPartLength = 5;
NSLog (@"%@", [string substringWithRange:(NSRange){range.location + firstPartLength, range.length - (firstPartLength + secondPartLength)}]
它给了我正确的结果“溢出”。但问题是在很多情况下,我不知道第一部分或第二部分的长度。那么,有没有一种方法可以获得应该在(.*)中的值

或者我必须决定通过找到(.)的位置来选择最丑陋的方法,并从那里计算第一部分和第二部分?但是在正则表达式中也可能有([a-z]),但是使用另一个正则表达式来获取()之间的值的位置,然后使用它来计算左、右部分的丑陋方式?如果我有更多,会发生什么?类似于“A(.)应该找到(.*)的答案。”我希望有一个数组作为结果,其值为[0]A后面的值和[1]to后面的值

我希望我的问题是清楚的


提前感谢,

您需要RegexKitLite库来执行正则表达式匹配:

在这之后,它几乎与PHP中的操作完全相同

我将添加一些代码来帮助您:

NSString *string     = @"stackoverflow.html";
NSString *expression = @"stack(.*)\\.html";
NSString *matchedString = [string stringByMatching:expression capture:1];

matchedString是@溢出,这正是您需要的。

在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

我认为NSRegularExpression比Perl、Ruby或许多其他语言更有用,NSRegularExpression功能强大,但在最常见的情况下,它使用段落来完成句子的工作。我喜欢这个库示例如何让您匹配一个表达式并在一行中捕获一个组。