2013-01-09 42 views
0

我想搜索字符串中的模式。在下面的代码中,模式字符串'*'可以是任何字符。搜索NSString中的模式

我从here得到了这个示例代码,但它不适用于我。

NSString *string; 
NSString *pattern; 
NSRegularExpression *regex; 


string = @"img=img_1.png or it can be img=img.png"; 
pattern = @"img=*.png"; 

regex = [NSRegularExpression 
     regularExpressionWithPattern:pattern 
     options:NSRegularExpressionCaseInsensitive 
     error:nil]; 

NSArray *matches = [regex matchesInString:string 
            options:0 
            range:NSMakeRange(0, [string length])]; 

NSLog(@"matches - %@", matches); 

for (NSTextCheckingResult *match in matches) 
{ 
    NSRange range = [match rangeAtIndex:1]; 
    NSLog(@"match: %@", [string substringWithRange:range]); 
} 

我想optput string要img_1.png & img.png

回答

1

改变你的模式:

pattern = @"img=(.*?).png"; 
+0

我得到这个O/p - > match:img_1.png或者它可以是img = img,其中ai想要img_1.png&im g.png – JiteshW

+0

已更新我的回答 – Andy

+0

谢谢,解决了我的问题。 – JiteshW

0

这种模式可以很好地工作:

NSString *pattern = @"(img=img[\\S]*\\.png)"; 

这些匹配是:

0 : {0, 13} - img=img_1.png 
1 : {27, 11} - img=img.png 

OR

与另一图案:

NSString *pattern = @"(img[^=][\\S]*png)"; 

的匹配是(没有IMG =部分):

0 : {4, 9} - img_1.png 
1 : {31, 7} - img.png